【问题标题】:Javascript reassigning array value no longer references?Javascript重新分配数组值不再引用?
【发布时间】:2022-01-02 15:38:07
【问题描述】:

不知道如何解释这个问题。这里有一些非常简单的代码来演示它。

我希望 testValue 和 testValue2 是 [20, 21, 22],因为它们是通过引用传递而不是通过值传递的,据我所知,并且看起来像因为它们更新了.push() 方法。

有人知道这里发生了什么吗?为什么我们重新分配原始数组后,testValue 和 testValue2 似乎都开始按值传递?

let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = testArray;

testArray.push(13);
testArray = [20, 21, 22];

console.log(testArray);
console.log(testValue);


//Different attempt
let testArray2 = [1, [10, 11, 12], 3, 4, 5];
let testValue2 = testArray2[1];

testArray2.push(13);
testArray2[1] = [20, 21, 22];

console.log(testArray2);
console.log(testValue2);

【问题讨论】:

  • 只是为了澄清:“因为它们是按引用传递而不是按值传递” - JavaScript 总是按值传递。但如果是对象,它不是对象本身,它是指向对象的“指针”:Is JavaScript a pass-by-reference or pass-by-value language?
  • testValue 有一个指向数组[1, [10, 11, 12], ...] 的指针,testArray 有一个指向数组[20, 21, 22] 的指针。 testArray2 存储指向[1, [10, 11, 12], ... ] 的指针,testValue2 存储指向[10, 11, 12] 的指针(in testArray2)。然后你只修改testArray2[1]指向in testArray2的数组,而不是testValue2的内容。
  • 恕我直言,我的“澄清”评论中的问题将成为一个很好的欺骗目标......
  • 感谢您的评论! “然后您只修改 testArray2[1] 在 testArray2 中指向的数组,而不是 testValue2 的内容” 是的,但是由于 testValue2 专门指向 testArray2 中的数组,它不应该也改变吗?那么为何不?它们指向同一个数组,对吧?
  • 没有。 testValue2 指向(是指向)A 的引用。然后用B 替换testArray2 中的“数组”(它的指针)。但这不会改变testValue2 的内容,它仍然指向(指向)A

标签: javascript arrays reference


【解决方案1】:

问题:位置记忆。

您使用testArray 创建新变量testValue,这两个变量具有相同的位置内存,然后您使用.push() 它会将新值推送到变量的位置内存,而不取决于您使用它的数组。

如果您不希望它们具有相同的位置记忆。使用这个:

// Array.from
let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = Array.from(testArray);

// spread operator
let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = [...testArray];

更多详情请查看这篇文章:

  1. https://backbencher.dev/articles/javascript-variables
  2. https://medium.com/@ethannam/javascripts-memory-model-7c972cd2c239

【讨论】:

    猜你喜欢
    • 2012-10-14
    • 2017-03-01
    • 2017-04-15
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 2016-09-12
    • 2020-09-23
    相关资源
    最近更新 更多