为什么改变一个数组会改变另一个? [英] Why does changing one array alters the other?
问题描述
考虑一下这段 javascript 代码:
Consider this tiny bit of javascript code:
var a = [1, 2, 3],
b = a;
b[1] = 3;
a; // a === [1, 3, 3] wtf!?
为什么当我更新b[1]"时a"会改变?我已经在 Firefox 和 Chrome 中对其进行了测试.例如,这不会发生在一个简单的数字上.这是预期的行为吗?
Why does "a" change when I update "b[1]"? I've tested it in Firefox and Chrome. This doesn't happen to a simple number for example. Is this the expected behaviour?
var a = 1,
b = a;
b = 3;
a; // a === 1 phew!
推荐答案
因为a"和b"引用同一个数组.他们没有两个;将a"的值分配给b"会将引用分配给数组,不是数组的副本.
Because "a" and "b" reference the same array. There aren't two of them; assigning the value of "a" to "b" assigns the reference to the array, not a copy of the array.
当您分配数字时,您是在处理原始类型.即使在 Number 实例上也没有更新值的方法.
When you assign numbers, you're dealing with primitive types. Even on a Number instance there's no method to update the value.
您可以在 Date 实例中看到相同的它们指向同一个对象"行为:
You can see the same "they're pointing to the same object" behavior with Date instances:
var d1 = new Date(), d2 = d1;
d1.setMonth(11); d1.setDate(25);
alert(d2.toString()); // alerts Christmas day
这篇关于为什么改变一个数组会改变另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!