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

前端 未结 8 1803
天命终不由人
天命终不由人 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 08:51

    This question is really old, but with ES6, there's a simpler way to do this using the spread operator:

    sourceArray.splice(index, 0, ...insertedArray)
    

    If you're using uncompiled javascript in the browser, be sure to check if it's supported in your target browser at https://kangax.github.io/compat-table/es6/#test-spread_(...)_operator.


    Also, this may be slightly off topic, but if you don't want or need to modify the original array, but could use a new array instead, consider this approach:

    mergedArray = sourceArray.slice(0, index).concat(insertedArray, sourceArray.slice(index))
    

提交回复
热议问题