如何判断[ ]或者{ }
(1) Array.isArray( )
console.log(Array.isArray([1,2])) //true
console.log(Array.isArray({"name":"zl"})) //false
(2) Object.prototype.toString
const a = [1,2,3];
const b = {"name":"lilei"};
const c = "hello world";
console.log(Object.prototype.toString.call(a)); //[object Array]
console.log(Object.prototype.toString.call(b)); //[object Object]
console.log(Object.prototype.toString.call(c)); //[object String]
使用apply的方法也可以;
(3)用instanceof判断
const a = [];
const b = {};
console.log(a instanceof Array) //true
console.log(a instanceof Object) //true
console.log(b instanceof Array) //false
由于typeof null, 数组,对象的返回值都是object,因此不能用来判断;
const a = [];
const b = {};
const c = null;
console.log(typeof a); //object
console.log(typeof b); //object
console.log(typeof c); //object
(4)用constructor判断
实例化的数组拥有constructor属性,指向其原型对象。
const a = [];
console.log(a.constructor);//function Array(){[native code]}
const b = {};
console.log(b.constructor);//function Object(){[native code]}
const c = null;
console.log(c.constructor);// Cannot read property 'constructor' of null
有一个缺点:就是当我们修改constructor的时候就会发生改变;
const a = [];
a.constructor = Object;
console.log(a.constructor == Array);//false
console.log(a.constructor == Object);//true
console.log(a instanceof Array);//true(拥有孙悟空的火眼金睛)
(5)用Object.prototype.isPrototypeOf判断
const a = [];
const b = {};
const c = null;
console.log(Array.prototype.isPrototypeOf(a)) //true
console.log(Array.prototype.isPrototypeOf(b)) //false
console.log(Array.prototype.isPrototypeOf(c)) //false
(6)用getPrototypeOf判断
console.log(Object.getPrototypeOf(a) === Array.prototype) //true
console.log(Object.getPrototypeOf(b) === Array.prototype) //false
console.log(Object.getPrototypeOf(c) === Array.prototype) //cannot convert undefined or null to object 无法转化为对象
其实许多的内容都可以从网上找到答案,也许很多人都遇到过这样的问题。我是那个需要亲自动手,实践才能搞明白的。嘻嘻。每天加油,继续进步。