我可以使用obj.constructor === Array来测试对象是否为Array吗? [英] Can I use `obj.constructor === Array` to test if object is Array?

查看:65
本文介绍了我可以使用obj.constructor === Array来测试对象是否为Array吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 obj.constructor === Array 来测试对象是否为建议的数组是正确的

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?

推荐答案

在某些情况下,它可以返回不同的值,但是 Array.isArray 将起作用.

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

一个窗口的 Array 对象与另一窗口中的 Array 对象不同.

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

构造函数属性可以被覆盖.

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

另一个对象也可以将 constructor 属性设置为 Array .

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

这篇关于我可以使用obj.constructor === Array来测试对象是否为Array吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆