2016-01-10 35 views
0

在JavaScript数组中,对象因此通过引用传递。所以array re/assignment reference changes

var a = ["a"]; 
var b = a; 
console.log(b); 
a[0] = "wtv"; 
console.log(b); 

会改变b值。

我不明白的是为什么

var a = ["a"]; 
var b = a; 
console.log(b); 
a = ["wtv"]; 
console.log(b); 

没有改变B值?这背后的推理是什么?

回答

4

因为内存a指向的值由分配a = ["wtv"];更改。

而在第一个示例中,您更改了零件/属性a,而内存a中的对象指向保持不变。

一种图像来解释它:

enter image description here

2

这是因为你b只是复制参考a

因此,他们有相同的参考副本,但他们各自有自己的该参考的副本。

var a = ["a"]; 

// b now holds a copy of the reference from a 
var b = a; 

// when you change a, b is unaffected since it has an independent reference 
// a now points to a new location in memory 
// a has a new reference, whereas b still has the reference from before 
a = ["wtv"]; 

然而,由于这两个变量具有相同的参考,即使他们是副本,您可以将对象或数组本身更改数据,并将它会影响这两个变量。

借此例如:

// a points to a location in memory 
var a = []; 

// we give a some value 
a["foo"] = 'bar'; 

// b now has a *copy* of a's location in memory 
var b = a; 

// since b shares the same location in memory as a, it has the same foo value 
console.log(b.foo); // => bar 

// we update a's foo value 
a["foo"] = 'baz'; 

// since b still shares the same location in memory as a, 
// it's pointing to the same foo from a, therefore it's also affected 
console.log(b.foo); // => baz 

@Hidde有一个伟大的形象,有助于想象这是怎么回事与存储指向在幕后。

1

随着a = ["wtv"];您指定全新的数组变量a。它与之前的参考无关。

1

在JavaScript的阵列也是一个对象和对象总是传送/通过引用指派。因此,这两个变量都有一个对同一个对象的引用,因此两个变量都会反映另一个对象的变化,因为它们都指向相同的值。

而在后一种情况下,你分配一个新值var a,这将被存储在不同的存储位置,而不是在其上存储的b之一,它是喜欢做

var a = 5; 
var b = a; 
a = a - 1; 
alert(b); // alerts 5 
alert(a); // alerts 4 
相似