最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I use `obj.constructor === Array` to test if object is Array? - Stack Overflow

programmeradmin0浏览0评论

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 patible with Array.isArray?

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 patible with Array.isArray?

Share Improve this question edited May 23, 2017 at 11:54 CommunityBot 11 silver badge asked Feb 12, 2015 at 0:34 Ali ShakibaAli Shakiba 21.3k18 gold badges65 silver badges89 bronze badges 3
  • you can also use the boolean return from "obj instanceof Array", but like your version, it only returns true for an Array of the same window scope. – kennebec Commented Feb 12, 2015 at 1:03
  • Do you have read any of the other answers on that question? blog.niftysnippets/2010/09/say-what.html – Bergi Commented Apr 1, 2015 at 20:08
  • @Bergi Yes, when I asked this question I was interested to learn more about obj.constructor === Class as well. – Ali Shakiba Commented Apr 1, 2015 at 20:14
Add a ment  | 

1 Answer 1

Reset to default 12

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
发布评论

评论列表(0)

  1. 暂无评论