Differentiating between arrays and “hashes” in Javascript

后端 未结 5 1661
再見小時候
再見小時候 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 13:42

    I think the most elegant way is to simply use the instanceof operator:

    if (myVar instanceof Array)
        doSomething();
    

    examples:

    [] instanceof Array           // true
    {} instanceof Array           // false
    {length:100} instanceof Array // false
    null instanceof Array         // false
    

    Edit:

    Be aware that it will fail when testing an object from another iFrame (see answers by @galambalazs and @bobince)

提交回复
热议问题