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

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

提交回复
热议问题