Differentiating between arrays and “hashes” in Javascript

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

    This typeof function is used to correct the array/object clash for the typeof operator, and the null/object clash. It does not however work across frames or across windows. See the source for a more advanced version that works across these.

    function typeOf(value) {
        var s = typeof value;
        if (s === 'object') {
            if (value) {
                if (value instanceof Array) {
                    s = 'array';
                }
            } else {
                s = 'null';
            }
        }
        return s;
    }
    

    Source: Douglas Crockford's Javascript site

提交回复
热议问题