1.typeof
我们能够使用typeof判断变量的身份,判断字符串得到string,数字和NaN得到number,函数会得到function等,但是判断数组,对象和null时都会得到object,详细请看js数据类型,这就是typeof的局限性,并不能准确的判断该变量的"真实身份"。那如何判断一个变量是数组还是对象?
2.instanceof
var arr = new Array();
var arr = ['aa','bb','cc'];
var obj = {
a: 'aa',
b: 'bb',
c: 'cc'
};
console.log(arr instanceof Array); //true
console.log(arr instanceof Object); //true
console.log(obj instanceof Array); //false
console.log(obj instanceof Object); //true
3.constructor
var arr = ['aa','bb','cc'];
var obj = {
'a': 'aa',
'b': 'bb',
'c': 'cc'
};
console.log(arr.constructor === Array); //true
console.log(arr.constructor === Object); //false
console.log(obj.constructor === Object); //true
4.Object.prototype.toString.call()
Object.prototype.toString.call()方法可以精准判断变量类型,它返回[object constructorName]的字符串格式,这里的constructorName就是call参数的函数名
var a = NaN;
var b= '222';
var c = null;
var d = false;
var e = undefined;
var f = Symbol();
var arr = ['aa','bb','cc'];
var obj = {
'a': 'aa',
'b': 'bb',
'c': 'cc'
};
var res = Object.prototype.toString.call(arr);
console.log(res); //[object Array]
var res2 = Object.prototype.toString.call(obj);
console.log(res2); //[object Object]
var res3 = Object.prototype.toString.call(a);
console.log(res3); //[object Number]
var res4 = Object.prototype.toString.call(b);
console.log(res4); //[object String]
var res4 = Object.prototype.toString.call(c);
console.log(res4); //[object Null]
var res5 = Object.prototype.toString.call(d);
console.log(res5); //[object Boolean]
var res6 = Object.prototype.toString.call(e);
console.log(res6); //[object Undefined]
var res7 = Object.prototype.toString.call(f);
console.log(res7); //[object Symbol]
网友评论