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?
那么,这里的逻辑(“引擎盖下的想法”)是什么,在一个样本中,它影响原始内容,但在另一个样本中则不影响?
Qyouu
相关分类