Memory of Reference Values in Javascript

风流意气都作罢 提交于 2021-02-17 03:27:19

问题


JavaScript stores Reference Values in Heap memory and thus variables stores to a pointer/address. So, if we change original variable, it changes the assigned one as well:

var cols = ['red', 'blue', 'green']
var newCols = cols

cols.push('orange')

console.log(cols) 
// returns ["red", "blue", "green", "orange"]
console.log(newCols)
// returns ["red", "blue", "green", "orange"]

However, when I experimenting for reference types, I find out that, when I am using indexing for assignment and push method they act in not same logic which I did not expect:

var cols = ['red', 'blue', 'green']
var newCols=cols[1]
cols[1] = "pink"
console.log(cols)
// returns > ["red", "pink", "green"]
console.log(newCols)
// returns > "blue"  WHY?

But:

var cols = ['red', 'blue', 'green']
var newCols=cols
newCols[3] = 'orange'
cols.push('yellow')

console.log(cols)
// returns > ["red", "blue", "green", "orange", "yellow"]
console.log(newCols)
// returns > ["red", "blue", "green", "orange", "yellow"] WHY?

So, what is the logic ('the idea under the hood') here that, in one sample, it affects original, but in another it does not?


回答1:


When you do

var newCols=cols[1]

you essentially take the reference to the value that cols[1] currently holds, and have newCols point to it too. For example, say cols[1], currently the 'blue' string, is at memory location #5432. Then doing newCols=cols[1] has newCols also point to #5432.

The array that cols is is also an array of references to memory locations. So ['red', 'blue', 'green'] could be thought of as [#987, #5432, #123]. Reassigning one of the indicies puts a new reference at that spot. After cols[1] = "pink", you can think of cols as now containing [#987, #333, #123].

The original item at #5432 - 'pink' - is not affected. newCols, which points to #5432, still points to 'pink'.

When you do

var newCols=cols

the whole array container is pointed to from two variables. Eg, both cols and newCols point to #55555. So mutating one will result in the other appearing to change as well.

(The "memory location" is a useful visualization, but it's not necessarily how it isn't how things work under the hood - this is just an easy way of thinking about it)



来源:https://stackoverflow.com/questions/64978894/memory-of-reference-values-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!