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

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

    You can also add such a function to the Array prototype, if you want something that is almost identical to the splice method. E.g.

    Array.prototype.spliceArray = function(index, n, array) {
        return Array.prototype.splice.apply(this, [index, n].concat(array));
    }
    

    Then usage would simply be:

    var array = ["A","B","C","","E","F"];
    
    array.splice(3,1,"D");
    // array is ["A","B","C","D","E","F"]
    
    array.spliceArray(3,3,["1","2","3"]);
    // array is ["A","B","C","1","2","3"]
    

    See it in action here: http://jsfiddle.net/TheMadDeveloper/knv2f8bb/1/

    Some notes:

    • The splice function modifies the array directly, but returns the an array of elements that were removed... not the spliced array.
    • While it's normally not recommended to extend core javascript classes, this is relatively benign with most standard frameworks.
    • Extending Array won't work in cases where specialized array classes are used, such as an ImageData data Uint8ClampedArray.
    0 讨论(0)
  • 2020-12-02 08:51

    You can use apply to avoid eval:

    var args = [start, number].concat(newItemsArray);
    Array.prototype.splice.apply(theArray, args);
    

    The apply function is used to call another function, with a given context and arguments, provided as an array, for example:

    If we call:

    var nums = [1,2,3,4];
    Math.min.apply(Math, nums);
    

    The apply function will execute:

    Math.min(1,2,3,4);
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-12-02 08:56

    There are a lot of clever answers here, but the reason you use splice is so that it puts the elements into the current array without creating another. If you have to create an array to concat() against so you can use apply() then you're creating 2 additional trash arrays! Sorta defeats the whole purpose of writing esoteric Javascript. Besides if you don't care about that memory usage stuff (and you should) just dest = src1.concat(src2); it is infinitely more readable. So here's is my smallest number of lines while staying efficient answer.

    for( let item of src ) dest.push( item );
    

    Or if you'd like to polyfill it and have a little better browser support back:

    src.forEach( function( x ) { dest.push(x); });
    

    I'm sure the first is more performant (it's a word ;), but not supported in all browsers out there in the wild.

    0 讨论(0)
  • 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/

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

    If you don't want to concatenate inserting items to first two parameters of Array.splice(), an elegant way is to use Function.bind() and Function.apply() together.

    theArray.splice.bind(null, startIndex, deleteCount).apply(newItemsArray);
    
    0 讨论(0)
提交回复
热议问题