为什么更改一个数组会改变另一个? [英] 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.
你可以看到相同的他们指向同一个对象的日期实例行为:
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屋!