Whats the best way to find out if an Object is an Array

后端 未结 4 1447
北荒
北荒 2021-02-13 21:07

As far as I know there are three ways of finding out if an object is an Array

by isArray function if implemented

Array.isArray()
         


        
4条回答
  •  孤街浪徒
    2021-02-13 21:59

    instanceof tests whether the given constructor (Array) is in the object's prototype chain, while your second approach only checks the actual type of the object. In other words, if your object inherits from Array, the second test will be true, but the first will be false. Now, it's not typically done to inherit from Array (it doesn't work right in IE), but walking the prototype chain presumably adds some overhead (especially if the object isn't an array).

提交回复
热议问题