简体   繁体   中英

Using splice with nested arrays in Javascript

I have an array in which all the elements are also arrays (of integers), called mainArray . I am trying to use splice() to add and remove its elements (subarrays).

Initially mainArray has a single element (an Array with one integer), I wish to delete it and add 3 new subarrays to mainArray , these are defined in arraysToAdd.

mainArray = new Array(new Array(1));
arraysToAdd = new Array(new Array(1,2), new Array(1,4), new Array(1,7));

alert(arraysToAdd.length); // Returns: 3: as expected

mainArray.splice(0,1,arraysToAdd);

alert(mainArray.length); // Returns: 1: I want this to be 3

I expect the length of mainArray at the end to be 3 (as it should contain 3 subarrays), but it seems splice() is flattening arraysToAdd and so mainArray ends up just being an array of integers.

What am I missing?

What you're missing is that you're adding an Array of Arrays to your Array of Arrays. You want to add each individual Array instead.

You can use .apply() to do this:

mainArray.splice.apply(mainArray, [0,1].concat(arraysToAdd));

So the 0 and 1 arguments you passed are joined with your arraysToAdd to form the arguments that you're going to pass to .splice() via .apply() .

Demo: http://jsfiddle.net/QLwLA/


Without .apply() , you would have needed to add them individually, like this:

mainArray.splice(0, 1, arraysToAdd[0], arraysToAdd[1], arraysToAdd[2]);

Demo: http://jsfiddle.net/QLwLA/1/

尝试这个:

mainArray.splice(0, 1, ...arraysToAdd)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM