let arr = [1, 2, 3]
console.log(arr.constructor === Array)
上面代码的输出结果是 true。
根据原型链
不应该是
console.log(arr.__proto__.constructor === Array)
为什么 arr.constructor === Array
的返回结果也是 true 呢?
let arr = [1, 2, 3]
console.log(arr.constructor === Array)
上面代码的输出结果是 true。
根据原型链
不应该是
console.log(arr.__proto__.constructor === Array)
为什么 arr.constructor === Array
的返回结果也是 true 呢?
@鸿则说的关于 constructor
的部分是对的。
但判断不应该用 instanceof
,而是要用 Array.isArray()
。
即便出于兼容不支持 ES6 的浏览器,也应该用 if (Object.prototype.toString.call(obj) === '[object Array]')
的方式。
9 回答9.8k 阅读
4 回答8.4k 阅读✓ 已解决
7 回答10.4k 阅读
5 回答8.7k 阅读
2 回答10.8k 阅读✓ 已解决
6 回答2k 阅读
4 回答11.6k 阅读
判断是否为数组推荐使用Array.isArray()。
instanceof
在使用iframe
的时候失效是因为iframe
有独立的window
。这是MDN的例子:但是以下判断还是有效的:
arr本身没有
![image.png image.png](/img/bVbGmPz)
constructor
属性但是使用
arr.constructor
的时候会根据原型链查找,所以此时arr.constructor
等于arr.__proto__.constructor
判断是否为数组推荐使用
instanceof