Skip to content

Instantly share code, notes, and snippets.

@imbyc
Last active May 26, 2020 02:41
Show Gist options
  • Save imbyc/6896de7a55d326992473fea2be0c6c24 to your computer and use it in GitHub Desktop.
Save imbyc/6896de7a55d326992473fea2be0c6c24 to your computer and use it in GitHub Desktop.
[js 比typeof运算符更准确的类型判断] 使用Object.prototype.toString判断 https://xugaoyi.com/pages/fd4a16d56b83c1bc/ #js
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"
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