为什么 splice() 会改变两个数组?
Why does splice() change both Arrays?
看下面的代码:
var x = [1, 2, 3], y;
y = x;
y.splice(0,0,4);
给出:
y = [4, 1, 2, 3] // (correct)
x = [4, 1, 2, 3] // (why did this change too?)
当我在 y
上调用 .splice()
时,为什么 x
数组发生变化?
对象(包括数组)通过引用传递(实际上,这就是它的作用......——纯粹主义者可能不同意这种说法)。 splice
方法改变了原始数组。因此,由于 x
和 y
指向同一个数组,y
上的 splice
也会更改 x
。要将 x
浅克隆到 y
,请执行 y = x.slice()
。 (请注意,x
中的任何对象都不会被克隆;它们将通过引用传递。)
var a = [1,2,3];
var b = a;
a[0] = 42;
alert(b[0]); // will show 42
var c = a.slice(); // explicitly makes a copy
a[1] = 6502;
alert(c[1]); // will show 2, not 6502
取自value type reference type object in javascript
看下面的代码:
var x = [1, 2, 3], y;
y = x;
y.splice(0,0,4);
给出:
y = [4, 1, 2, 3] // (correct)
x = [4, 1, 2, 3] // (why did this change too?)
当我在 y
上调用 .splice()
时,为什么 x
数组发生变化?
对象(包括数组)通过引用传递(实际上,这就是它的作用......——纯粹主义者可能不同意这种说法)。 splice
方法改变了原始数组。因此,由于 x
和 y
指向同一个数组,y
上的 splice
也会更改 x
。要将 x
浅克隆到 y
,请执行 y = x.slice()
。 (请注意,x
中的任何对象都不会被克隆;它们将通过引用传递。)
var a = [1,2,3];
var b = a;
a[0] = 42;
alert(b[0]); // will show 42
var c = a.slice(); // explicitly makes a copy
a[1] = 6502;
alert(c[1]); // will show 2, not 6502
取自value type reference type object in javascript