2016-01-10 64 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 
相似