I want to replace elements in some array from 0 element, with elements of another array with variable length. Like:
var arr = new Array(10), anotherArr = [1, 2, 3], result;
result = anotherArr.concat(arr);
result.splice(10, anotherArr.length);
Is there some better way?
You can use the
splice
method to replace part of an array with items from another array, but you have to call it in a special way as it expects the items as parameters, not the array.The
splice
method expects parameters like(0, anotherArr.Length, 1, 2, 3)
, so you need to create an array with the parameters and use theapply
method to call thesplice
method with the parameters:Example:
Output:
Demo: http://jsfiddle.net/Guffa/bB7Ey/