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

后端 未结 4 1448
北荒
北荒 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:58

    If what you're trying to do is to decide whether a parameter passed to you is an array that you should iterate over, there's a fair amount of code out there that just looks for a .length attribute and treats as an array or a pseudo-array if that attribute is present.

    This is because there are lots of things that aren't actually arrays (but are pseudo arrays with array like capabilities) that you may want your code to treat like an array. Examples of some of these kinds of things are a jQuery object or a nodeList returned from many DOM calls. Here's a code example:

    // accepts:
    //    single DOM element
    //    array of DOM elements
    //    nodeList as returned from various DOM functions like getElementsByClassName
    //    any array like object with a .length attribute and items in numeric indexes from 0 to .length-1 like a jQuery object
    function hideElements(input) {
        if (input.length !== undefined) {
            for (var i = 0, len = input.length; i < len; i++) {
                input[i].style.display = "none";
            }
        } else {
            input.style.display = "none";
        }
        return(input);
    }
    

    The jQuery .each() function also just tests the parameter passed to it for .length (and verifying that it's not a function) before deciding it's something it should iterate like an array.

    If that isn't the problem you're trying to solve, I can find two references to using the first technique:

    1. jQuery's implementation of isArray uses the first technique.
    2. MDN (Mozilla Developer Network) recommends the first one here.

提交回复
热议问题