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]')
的方式。
13 回答12.9k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
6 回答1.1k 阅读
3 回答1.3k 阅读✓ 已解决
判断是否为数组推荐使用Array.isArray()。
instanceof
在使用iframe
的时候失效是因为iframe
有独立的window
。这是MDN的例子:但是以下判断还是有效的:
arr本身没有

constructor
属性但是使用
arr.constructor
的时候会根据原型链查找,所以此时arr.constructor
等于arr.__proto__.constructor
判断是否为数组推荐使用
instanceof