How to insert an item into an array at a specific index (JavaScript)?

后端 未结 20 2176
灰色年华
灰色年华 2020-11-21 07:05

I am looking for a JavaScript array insert method, in the style of:

arr.insert(index, item)

Preferably in jQuery, but any JavaScript implem

20条回答
  •  Happy的楠姐
    2020-11-21 07:42

    Custom array insert methods

    1. With multiple arguments and chaining support

    /* Syntax:
       array.insert(index, value1, value2, ..., valueN) */
    
    Array.prototype.insert = function(index) {
        this.splice.apply(this, [index, 0].concat(
            Array.prototype.slice.call(arguments, 1)));
        return this;
    };
    

    It can insert multiple elements (as native splice does) and supports chaining:

    ["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
    // ["b", "X", "Y", "Z", "c"]
    

    2. With array-type arguments merging and chaining support

    /* Syntax:
       array.insert(index, value1, value2, ..., valueN) */
    
    Array.prototype.insert = function(index) {
        index = Math.min(index, this.length);
        arguments.length > 1
            && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
            && this.insert.apply(this, arguments);
        return this;
    };
    

    It can merge arrays from the arguments with the given array and also supports chaining:

    ["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
    // "a-b-V-W-X-Y-Z-c-d"
    

    DEMO: http://jsfiddle.net/UPphH/

提交回复
热议问题