gistfile1.txt /** * 对象数据类型的判断 */// Object.prototype.toString() Object.prototype.toString.call(1); // "[object Number]"Object.prototype.toString.call(null); // "[object Null]"// typeof 缺点是除 function 外的引用类型
/**
* 对象数据类型的判断
*/
// Object.prototype.toString()
Object.prototype.toString.call(1); // "[object Number]"
Object.prototype.toString.call(null); // "[object Null]"
// typeof 缺点是除 function 外的引用类型都统一为 "object"
typeof null; // "object"
typeof {}; // "object"
typeof NaN; // "number" 这个也是个坑
// instanceof 可用于区别 null 和 object
null instanceof Object; // false
// 一个判断数据类型(包括 es6 的 Set 和 Map 对象)的函数
function getType(value) {
let type = Object.prototype.toString.call(value).match(/^\[object (.*)\]$/)[1].toLowerCase();
if ( type === 'string' && typeof type === 'object' ) {
return 'object';
}
// PhantomJS has type "DOMWindow" for null
if ( type === null ) {
return 'null';
}
// PhantomJS has type "DOMWindow" for undefined
if ( type === undefined ) {
return 'undefined';
}
return type;
}
