Last active
May 26, 2020 02:41
-
-
Save imbyc/6896de7a55d326992473fea2be0c6c24 to your computer and use it in GitHub Desktop.
[js 比typeof运算符更准确的类型判断] 使用Object.prototype.toString判断 https://xugaoyi.com/pages/fd4a16d56b83c1bc/ #js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var type = function (o){ | |
var s = Object.prototype.toString.call(o) | |
return s.match(/\[object (.*?)\]/)[1].toLowerCase() | |
} | |
type({}); // "object" | |
type([]); // "array" | |
type(5); // "number" | |
type(null); // "null" | |
type(); // "undefined" | |
type(/abcd/); // "regex" | |
type(new Date()); // "date" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var type = function (o){ | |
var s = Object.prototype.toString.call(o); | |
return s.match(/\[object (.*?)\]/)[1].toLowerCase(); | |
}; | |
['Null', | |
'Undefined', | |
'Object', | |
'Array', | |
'String', | |
'Number', | |
'Boolean', | |
'Function', | |
'RegExp' | |
].forEach(function (t) { | |
type['is' + t] = function (o) { | |
return type(o) === t.toLowerCase(); | |
}; | |
}); | |
type.isObject({}) // true | |
type.isNumber(NaN) // true | |
type.isRegExp(/abc/) // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment