【发布时间】:2020-11-24 01:15:02
【问题描述】:
JavaScript 将引用值存储在堆内存中,因此变量存储到指针/地址。因此,如果我们更改原始变量,它也会更改分配的变量:
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"]
但是,当我尝试引用类型时,我发现当我使用索引进行赋值和推送方法时,它们的行为与我没想到的逻辑不同:
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?
但是:
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?
那么,这里的逻辑(“引擎盖下的想法”)是什么?
【问题讨论】:
-
newCols 在第二个代码中被赋值——它没有“指向”一个值
标签: javascript memory