我有2个数组:A和B,当我改变一个时都改变。有没有办法在不改变另一个的情况下编辑一个。
a = [[0,0,0,0,0],[0,0,0,0,0]]
b = [[1,2,3,4,5],[6,7,8,9,10]]
a = b.slice(0)
a[0][0] = 10
console.log(a) /* [[10,2,3,4,5],[6,7,8,9,10]] */
console.log(b) /* [[10,2,3,4,5],[6,7,8,9,10]] */
a很好,但我需要b留[[1,2,3,4,5],[6,7,8,9,10]]
答案 0 :(得分:4)
执行splice
时,您更改了a
和b
的引用,但是,数组b中的数组引用仍然共享引用,因此,请将代码更新为以下内容。使用Array.map
a = [[0,0,0,0,0],[0,0,0,0,0]]
b = [[1,2,3,4,5],[6,7,8,9,10]]
a = b.map(x => [...x])
a[0][0] = 10
console.log(a) /* [[10,2,3,4,5],[6,7,8,9,10]] */
console.log(b) /* [[1,2,3,4,5],[6,7,8,9,10]] */
答案 1 :(得分:2)
您可以使用map
到slice
每个数组。
a = [[0,0,0,0,0],[0,0,0,0,0]]
b = [[1,2,3,4,5],[6,7,8,9,10]]
a = b.map(o=>o.slice(0));
a[0][0] = 10
console.log(a);
console.log(b);
Doc:map()
答案 2 :(得分:2)
您使用Array#slice
获取浅表副本,这意味着嵌套数组由其对象引用获取。
您可以使用Array#map
检查数组并以递归方式映射这些数据。
const deep = a => Array.isArray(a) ? a.map(deep) : a;
var a = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
b = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]];
a = b.map(deep);
a[0][0] = 10;
console.log(a);
console.log(b);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)
slice(),与Object.freeze()一样,范围较浅,因此可行:
var a = [1,2,3,4];
var b = a.slice(0);
a[0] = 10;
console.log(b); // [1, 2, 3]
console.log(a); // [10, 2, 3, 4]
但这不起作用:
var a = [[0,0,0,0,0],[0,0,0,0,0]]; //multidimensional!
var b = [[1,2,3,4,5],[6,7,8,9,10]];
a = b.slice(0);
a[0][0] = 10;
console.log(a);
console.log(b);
然后,密钥与slice()
,for
或其他内容深入,以下是一个使用示例:
var a = [];
for (var i = 0, len = b.length; i < len; i++) {
a[i] = b[i].slice();
}
请记住, const 无法工作:
var a = [[0,0,0,0,0],[0,0,0,0,0]];
const b = [[1,2,3,4,5],[6,7,8,9,10]];// doesn't work
var a = b.slice(0);
a[0][0] = 10; // a changes b
console.log(a);
console.log(b);