关键词:数据类型
方法
- tyoeof
console.log(typeof 1); // number
console.log(typeof null);// object
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof function (argument) {});// function
console.log(typeof undefined);// undefined
console.log(typeof 'str'); // string
console.log(typeof false); // boolean
- Object.prototype.toString.call
var arr =[];
var isArray = Object.prototype.toString.call(arr) == "[object Array]"
console.log(isArray);
var gettype=Object.prototype.toString
gettype.call('aaaa' // [object String]
gettype.call(2222) // [object Number]
gettype.call(true) // [object Boolean]
gettype.call(undefined) // [object Undefined]
gettype.call(null) // [object Null]
gettype.call({}) // [object Object]
gettype.call([]) // [object Array]
gettype.call(function(){}) // [object Function]
- 这种方法还能判断出DOM元素的类型
var oDiv = document.querySelector('div');
console.log(typeof oDiv);
var gettype=Object.prototype.toString
console.log(gettype.call(oDiv)) //[object HTMLDivElement]
- isntanceof
var arr = [];
console.log(arr instanceof Array); // true
下面我们用一个小例子来说明Object.prototype.toString.call的优点
var a = 'ferrinte';
var b = new String('ferrinte');
// a 和 b 同属于字符串
console.log(a.substr == b.substr); // true
// typeof 不能准确判断类型
console.log(typeof a); // string
console.log(typeof b); // object
// instanceof 也不能
console.log(a instanceof String); // false
console.log(b instanceof String); // true
// a和b竟然不全等
console.log(a == b); //true
console.log(a === b); // false
// 关键时候还是Object.prototype.toString.call()靠谱
console.log(Object.prototype.toString.call(a)); // [object String]
console.log(Object.prototype.toString.call(b)); // [object String]