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

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

    UPDATE: ES6 version

    If your coding in ES6 you can use the "spread operator" (...)

    array.splice(index, 0, ...arrayToInsert);
    

    To learn more about the spread operator see mozilla documentation.

    The 'old' ES5 way

    If you wrap the top answer into a function you get this:

    function insertArrayAt(array, index, arrayToInsert) {
        Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
    }
    

    You would use it like this:

    var arr = ["A", "B", "C"];
    insertArrayAt(arr, 1, ["x", "y", "z"]);
    alert(JSON.stringify(arr)); // output: A, x, y, z, B, C
    

    You can check it out in this jsFiddle: http://jsfiddle.net/luisperezphd/Wc8aS/

提交回复
热议问题