Differentiating between arrays and “hashes” in Javascript

后端 未结 5 1730
再見小時候
再見小時候 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:41

    something instanceof Array works fine within a single document, but will fail if you start passing arrays between different windows, because the Array from one window is a different object from Array on another. If you have no intention of doing cross-window-scripting (and in general, it's worth avoiding) I would recommend sticking with this.

    If you need cross-window support, things are a bit more complex. In the future the story is simple, as ECMAScript Fifth Edition defines a function to do exactly this:

    Array.isArray([1]);   // -> true
    

    You should use this functionality where available as it's the only reliable and standards-endorsed way. However, many of today's browsers don't support it yet.

    Where it isn't available you have to rely on Object#toString serialisation, which is ugly and slightly dodgy. Although it will in general work reliably with today's browsers, there are imaginable cases where it might not (primarily to do with host objects).

    You can hack this fallback method into Array on browsers that don't support it, and then use Array.isArray at all times:

    if (!('isArray' in Array)) {
        Array.isArray= function(o) {
            return Object.prototype.toString.call(o)==='[object Array]';
        };
    }
    

    As for constructor, never use it. It's not available everywhere and it doesn't do what you think. Using it is almost always a mistake.

提交回复
热议问题