Creating array-like objects in JavaScript

后端 未结 5 1247
轻奢々
轻奢々 2020-12-02 15:53

In JavaScript, there are objects that pretend to be arrays (or are \"array-like\"). Such objects are arguments, NodeLists (returned from get

5条回答
  •  执笔经年
    2020-12-02 16:51

    Depends specifically on the console. For custom objects in Chrome's developer console, and Firebug you'll need both the length and splice properties. splice will also have to be a function.

    a = {
        length: 0,
        splice: function () {}
    }
    console.log(a); //[]
    

    It's important to note, however, that there is no official standard.

    The following code is used by jQuery (v1.11.1) internally to determine if an object should use a for loop or a for..in loop:

    function isArraylike( obj ) {
        var length = obj.length,
            type = jQuery.type( obj );
    
        if ( type === "function" || jQuery.isWindow( obj ) ) {
            return false;
        }
    
        if ( obj.nodeType === 1 && length ) {
            return true;
        }
    
        return type === "array" || length === 0 ||
            typeof length === "number" && length > 0 && ( length - 1 ) in obj;
    }
    

    Note that it's possible to have an object that appears in the console as an array ([]) but that gets iterated over with a for..in loop in jQuery, or an object that appears as an object in the console ({}) but that gets iterated over with a for loop in jQuery.

提交回复
热议问题