有以下 3 个判断数组的方法,请分别介绍它们之间的区别和优劣Object.prototype.toString.call() 、 instanceof 以及 Array.isArray()
个人题解
1、Object.prototype.toString.call(),是使用原型上的toString()方法,输出为[Object xxxxx],通过xxxxx的内容判断当前的类型.目前大部分判断类型都是基于此方法,比较准确
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| console.log(Object.prototype.toString.call([1, 2, 3])); console.log(Object.prototype.toString.call(1)); console.log(Object.prototype.toString.call(NaN)); console.log(Object.prototype.toString.call("1")); console.log(Object.prototype.toString.call(() => {})); console.log(Object.prototype.toString.call(undefined)); console.log(Object.prototype.toString.call(null)); console.log(Object.prototype.toString.call({})); console.log(Object.prototype.toString.call(/reg/)); console.log(Object.prototype.toString.call(true)); console.log(Object.prototype.toString.call(Symbol)); console.log(Object.prototype.toString.call(new Set())); console.log(Object.prototype.toString.call(new Map())); console.log(Object.prototype.toString.call(new Date())); console.log(Object.prototype.toString.call(new WeakSet())); console.log(Object.prototype.toString.call(new WeakMap()));
|
2、instanceof是基于原型链的判断方法,一个数组会找到他的原型是不是属于array,如果是返回true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| let fsimpleStr = "This is a simple string"; let fmyString = new String(); let fnewStr = new String("String created with LETructor"); let fmyDate = new Date(); let fmyObj = {}; let fmyNonObj = Object.create(null); simpleStr instanceof String; myString instanceof String; newStr instanceof String; myString instanceof Object;
myObj instanceof Object; ({}) instanceof Object; myNonObj instanceof Object;
myString instanceof Date;
myDate instanceof Date; myDate instanceof Object; myDate instanceof String;
class Parent {} class Child extends Parent {} let demo = new Child(); console.log(demo instanceof Child); console.log(demo instanceof Parent); console.log(demo instanceof Object);
|
3、Array.isArray(),Array对象上提供的判断是否是数组的方法,比较准确
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| Array.isArray([1, 2, 3]);
Array.isArray({foo: 123});
Array.isArray("foobar");
Array.isArray(undefined);
Array.isArray([]); Array.isArray([1]); Array.isArray(new Array()); Array.isArray(new Array('a', 'b', 'c', 'd'))
Array.isArray(Array.prototype);
Array.isArray(); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)) Array.isArray({ __proto__: Array.prototype });
|
相关链接
第 21 题:有以下 3 个判断数组的方法,请分别介绍它们之间的区别和优劣Object.prototype.toString.call() 、 instanceof 以及 Array.isArray()
MDN isArray
MDN instanceof