简体   繁体   English

在Javascript中对嵌套数组使用拼接

[英]Using splice with nested arrays in Javascript

I have an array in which all the elements are also arrays (of integers), called mainArray . 我有一个数组,其中所有元素也是(整数)数组,称为mainArray I am trying to use splice() to add and remove its elements (subarrays). 我正在尝试使用splice()添加和删​​除其元素(子数组)。

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具有一个元素(一个具有一个整数的Array),我希望将其删除并将3个新的子mainArray添加到mainArray ,这些在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. 我期望mainArray的末尾长度为3(因为它应该包含3个子数组),但是splice()似乎将arraysToAdd平,所以mainArray最终只是一个整数数组。

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: 您可以使用.apply()执行此操作:

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() . 因此,您传递的01参数与arraysToAdd结合arraysToAdd ,形成要通过.splice()传递给.splice() .apply()

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


Without .apply() , you would have needed to add them individually, like this: 如果没有.apply() ,则需要单独添加它们,如下所示:

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

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

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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