How do jQuery objects imitate arrays?

后端 未结 2 685
忘掉有多难
忘掉有多难 2020-12-06 01:24

jQuery objects act like arrays without polluting native prototypes. How is this achieved?

I know it\'s not just objects with numeric keys - so perhaps it\'s just a m

2条回答
  •  离开以前
    2020-12-06 02:16

    Look in jquery code (development), line 139:

    // Force the current matched set of elements to become
    // the specified array of elements (destroying the stack in the process)
    // You should use pushStack() in order to do this, but maintain the stack
    setArray: function( elems ) {
        // Resetting the length to 0, then using the native Array push
        // is a super-fast way to populate an object with array-like properties
        this.length = 0;
        Array.prototype.push.apply( this, elems );
            return this;
    },
    

    This is because any result of jquery queries is array.

提交回复
热议问题