views:

252

answers:

1

Is there a better way than this to splice an array into another array in javascript

var string = 'theArray.splice('+start+', '+number+',"'+newItemsArray.join('","')+'");';
eval(string);
+3  A: 

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);
CMS
cheers - exactly what I needed
wheresrhys
Although, it turns out I need to do Array.prototype.splice.apply(theArray, [start, number].concat(newItemsArray)) as all the arguments, not just some, must be in one array.
wheresrhys
I just found this too, exactly what I needed as well :)
Chris Burt-Brown
Me too, nice one. Second time you've sorted me out today, CMS! ;)
Nick Wiggill
@Nick, @Chris, glad to help! :)
CMS