Can I use `obj.constructor === Array` to test if object is Array?

柔情痞子 提交于 2021-02-20 19:27:26

问题


Is it correct to use obj.constructor === Array to test if an object is an array as suggested here? Does it always returns correct answer compatible with Array.isArray?


回答1:


Depends, there are a few scenarios where it can return a different value, but Array.isArray will work.

The Array object for one window is not the the same Array object in another window.

var obj = someIframe.contentWindow.someArray;
console.log(obj.constructor === Array);//false
console.log(Array.isArray(obj));//true

The constructor property can be overwritten.

var obj = [];
obj.constructor = null;
console.log(obj.constructor === Array);//false
console.log(Array.isArray(obj));//true

Another object can also set the constructor property to Array.

var obj = {};
obj.constructor = Array;
console.log(obj.constructor === Array);//true
console.log(Array.isArray(obj));//false


来源:https://stackoverflow.com/questions/28467266/can-i-use-obj-constructor-array-to-test-if-object-is-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!