简体   繁体   English

使用javascript中的拼接方法从数组数组中删除元素

[英]Removing element from an array of arrays of arrays using the splice method in javascript

I have an array of arrays of arrays and I'm trying to remove an element from a sub-sub array.我有一个数组数组,我正在尝试从子子数组中删除一个元素。 The problem is the element is removed from all my sub-sub arrays.问题是该元素已从我的所有子子数组中删除。 See code below:请参见下面的代码:

let list = Array(9).fill(Array(9).fill([1,2,3,4,5,6,7,8,9]));
list[0][0].splice(3,1);
console.log(list[0][0],list[2][1],list)

Please let me know if you know how to solve that.如果您知道如何解决,请告诉我。

Array.prototype.fill fills the array with the exact same value that was provided to it. Array.prototype.fill用提供给它的完全相同的值填充数组。 This is not a problem when filling the array with immutable values ( like numbers, strings ) but it's usually a problem with mutable values ( like objects, arrays ).用不可变值(如数字、字符串)填充数组时这不是问题,但通常是可变值(如对象、数组)的问题。

So, if you mutate one value in the array you would notice the change at all other places because all of them refer to the exact same value.所以,如果你改变数组中的一个值,你会注意到所有其他地方的变化,因为它们都引用了完全相同的值。 Refer to example below for better understanding.请参阅下面的示例以更好地理解。

 let nums = [1]; let arr = Array(2).fill(nums); // mutating nums nums[0] = 5; // the change is visible in arr as well console.log(arr[0]); // [ 5 ] // and it's visible at both the indicies console.log(arr[1]); // [ 5 ] // mutating arr arr[0][0] = 10; // change is visible in nums as well console.log(nums); // [ 10 ] // and also at index 1 console.log(arr[1]); // [ 10 ]

You can use Array.from instead.您可以改用Array.from

 let list = Array.from({ length: 9 }, () => Array.from({ length: 9 }, () => [1, 2, 3, 4, 5, 6, 7, 8, 9]) ); list[0][0].splice(3, 1); console.log(list[0][0]); // [ 1, 2, 3, 5, 6, 7, 8, 9 ] console.log(list[1][0]); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

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

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