Differentiating between arrays and “hashes” in Javascript

后端 未结 5 1666
再見小時候
再見小時候 2021-02-07 13:29

In order to make the syntax for one of my functions nicer, I need to be able to tell whether a specific parameter is an array or \"hash\" (which I know are just objects).

<
5条回答
  •  再見小時候
    2021-02-07 14:08

    You could check the length property as SLaks suggested, but as soon as you pass it a function object you'll be surprised, because it in fact has a length property. Also if the object has a length property defined, you'll get wrong result again.

    Your best bet is probably:

    function isArray(obj) {
        return Object.prototype.toString.call(obj) === "[object Array]";
    }
    

    jQuery uses it, and a "couple of" other people... :)

    It is more fail proof than the instanceof way. The method is also suggested by the following article:

    'instanceof' considered harmful (or how to write a robust 'isArray') (@kagax)

    Another thing to add that this function is almost identical to the Array.isArray function in ES 5 spec:

    15.4.3.2 Array.isArray ( arg )

    1. If Type(arg) is not Object, return false.
    2. If the value of the [[Class]] internal property of arg is "Array", then return true.
    3. Return false.

提交回复
热议问题