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

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

我有一个由数组组成的数组,我正在尝试从子子数组中删除一个元素。问题是该元素已从我所有的子子数组中删除。请参阅下面的代码:

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)

如果你知道如何解决这个问题,请告诉我。

Array.prototype.fill 用提供给它的完全相同的值填充数组。当用不可变值(如数字、字符串)填充数组时,不是问题,但通常是可变值(像对象、数组).

因此,如果您改变数组中的一个值,您会注意到所有其他地方的变化,因为它们都引用完全相同的值。请参阅下面的示例以更好地理解。

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 ]

您可以改用 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 ]