A better way to splice an array into an array in javascript

前端 未结 8 1789
天命终不由人
天命终不由人 2020-12-02 08:36

Is there a better way than this to splice an array into another array in javascript

var string = \'theArray.splice(\'+start+\', \'+number+\',\"\'+newItemsArr         


        
相关标签:
8条回答
  • 2020-12-02 09:02

    I wanted to have a function which would take only part of the source array so I have mine slightly different based off CMS's answer

    function spliceArray(array, index, howmany, source, start, end) {
        var arguments;
      if( source !== undefined ){
        arguments = source.slice(start, end);
        arguments.splice(0,0, index, howmany);
      } else{
       arguments = [index, howmany];
      }
        return Array.prototype.splice.apply(array, arguments)
    }
    
    Array.prototype.spliceArray = function(index, howmany, source, start, end) {
        return spliceArray(this, index, howmany, source, start, end);
    }
    

    You can see it at: https://jsfiddle.net/matthewvukomanovic/nx858uz5/

    0 讨论(0)
  • 2020-12-02 09:04

    The answers above that involve splice.apply and insert the array in a one liner will blow up the stack in a stack overflow for large array. See example here: http://jsfiddle.net/gkohen/u49ku99q/ You might have to slice and and push each item of the inserted and remaining part of the original array for it to work. See fiddle: http://jsfiddle.net/gkohen/g9abppgy/26/

    Array.prototype.spliceArray = function(index, insertedArray) {
       var postArray = this.splice(index);
       inPlacePush(this, insertedArray);
       inPlacePush(this, postArray);
    
       function inPlacePush(targetArray, pushedArray) {
    // Not using forEach for browser compatability
           var pushedArrayLength = pushedArray.length;
           for (var index = 0; index < pushedArrayLength; index++) {
               targetArray.push(pushedArray[index]);
           }
       }
    }
    
    0 讨论(0)
提交回复
热议问题