javascript - 非等于数组同时更改值javascript

标签 javascript arrays multidimensional-array

请检查以下...

var arr = [["test", 1], ["test", 3], ["test", 5]]
var otherArr = arr.slice(0) //should be a new array with a copy of arr

当我评估 arr === otherArr 时,结果是 FALSE

当我执行以下操作时,尝试更改第一个数组值:

otherArr[0][1] = otherArr[0][1] + 5;

它也改变了原来的数组(arr)

arr[0][1] === otherArr[0][1] 评估为 TRUE

但是 arr === otherArr 的计算结果为 FALSE

请帮助我理解这一点以避免它。

最佳答案

这是最好的视觉解释。想象一下 arr 如下图。它实际上由 3 个数组组成,一个引用另外两个:

arr [     0      ,      1      ]
          |             |
          v             v
      ['test', 1], ['test', 5]

当您执行 otherArr.slice(0) 时,它会创建一个“浅拷贝” - 一个新数组,但具有相同的内容原始数组。这意味着 arrotherArr 是两个独立的数组,但指向相同的内容。 arr[0]otherArr[0]是同一个对象,arr[1]otherArr[是同一个对象1]

arr      [     0      ,      1      ]
               |             |
               v             v
           ['test', 1], ['test', 5]
               ^             ^
               |             |
otherArr [     0      ,      1      ]

现在回答您的问题:

When i evaluate arr === otherArr the result is FALSE.

如前所述,arrotherArr是两个不同的数组,导致===失败。对于非基元,=== 检查身份(即它是同一个对象吗?)。另请注意,===== 不是结构检查(即它们看起来一样吗?)。

When i do the following, trying to change first array value:

otherArr[0][1] = otherArr[0][1] + 5;

it also changes the original array (arr)

arr[0][1] === otherArr[0][1] evaluates to TRUE

回到我们的图表,您实际上正在做的是更改两个数组引用的对象的内容(在本例中,现在是 ['test', 6])。

arr      [     0      ,      1      ]
               |             |
               v             v
           ['test', 6], ['test', 5]
               ^             ^
               |             |
otherArr [     0      ,      1      ]

关于javascript - 非等于数组同时更改值javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52085758/

相关文章:

javascript - 未捕获的 TypeError : window. initMap 不是函数

php - 如何将一个数组的条目随机插入另一个数组

javascript - 循环遍历数组中的 json 响应

java - 将 2D ArrayList<String> 转换为 2D 字符串数组

javascript - Highcharts 将每个系列的数据标签分开

javascript - CSS 转换在 Safari 中立即发生

c - 如何在 C 中释放 malloc 的二维数组?

php - 分组输出多维数组

Javascript 显示和隐藏函数

java - 如何将所有偶数移动到数组的前面?