我正在尝试练习不变性的概念。我使用 spliceTest
数组作为创建数组副本并改变它们的主要引用。当我声明 removeOneItem
变量时,我遇到了问题,我无法使用 spliceTest
的相同引用声明新的传播变量。
const removeOneItem = [...spliceTest.splice(0,0), ...spliceTest.splice(1)];
const removeFive = [...spliceTest.splice(0,4), ...spliceTest.splice(5)];
const spreadTest = [...spliceTest];
console.log('removeOneItem:', removeOneItem)
console.log('spreadTest:', spreadTest, spliceTest)
console.log('removeFive:', removeFive)
Results::::::::::::
removeOneItem: [ 2, 3, 4, 5, 6, 7, 8, 9 ]
spreadTest: [] []
removeFive: [ 1 ]
最佳答案
根据 MDN :
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
这意味着拼接操作会更改您的数组
关于javascript - 尝试使用扩展运算符创建数组的副本,但有些数组是如何变异的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59880442/