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

后端 未结 20 2150
灰色年华
灰色年华 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条回答
  •  失恋的感觉
    2020-11-21 07:48

    For proper functional programming and chaining purposes an invention of Array.prototype.insert() is essential. Actually splice could have been perfect if it had returned the mutated array instead of a totally meaningless empty array. So here it goes

    Array.prototype.insert = function(i,...rest){
      this.splice(i,0,...rest)
      return this
    }
    
    var a = [3,4,8,9];
    document.write("
    " + JSON.stringify(a.insert(2,5,6,7)) + "
    ");

    Well ok the above with the Array.prototype.splice() one mutates the original array and some might complain like "you shouldn't modify what doesn't belong to you" and that might turn out to be right as well. So for the public welfare i would like to give another Array.prototype.insert() which doesn't mutate the original array. Here it goes;

    Array.prototype.insert = function(i,...rest){
      return this.slice(0,i).concat(rest,this.slice(i));
    }
    
    var a = [3,4,8,9],
        b = a.insert(2,5,6,7);
    console.log(JSON.stringify(a));
    console.log(JSON.stringify(b));

提交回复
热议问题