判断JS如何区分对象和数组使用typeof是不行的,直接上方法代码:
一、直接使用内置方法isArray来判断,当然,只能判断是否是数组,对象还需要另外再判断
const a = [1, 2, 3, 4];
const b = {"name": "小白-起航"};
console.log(Array.isArray(a)) //true
console.log(Array.isArray(b)) //false
二、使用constructor来判断
`const a = [2, 4, 3];
const b = {"name": "小白-起航"};
console.log(a.constructor == Array); //true
console.log(b.constructor == Object); //true`
三、instanceOf运算符。左边是待测试对象,右边是构造函数。
凡是用new()构造函数创建出的对象,都称之为构造函数的实例。
const obj = {"name": "小白-起航"};
const arr = [1, 2, 3];
console.log((obj instanceof Array)); //false
console.log((arr instanceof Array)); //true
在此记录,希望有所帮助,—以前自己的账号找不到了。这是个新CSDN账号,所以好多笔记什么的也没有了,,