请检查以下...
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)
时,它会创建一个“浅拷贝” - 一个新数组,但具有相同的内容原始数组。这意味着 arr
和 otherArr
是两个独立的数组,但指向相同的内容。 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.
如前所述,arr
和otherArr
是两个不同的数组,导致===
失败。对于非基元,===
检查身份(即它是同一个对象吗?)。另请注意,===
和 ==
不是结构检查(即它们看起来一样吗?)。
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/