根据MDN文档调用 array.slice()将创建数组的浅表副本。
According the MDN documentation calling array.slice() will create a shallow copy of the array.
请参阅此切片的MDN链接()。
但是,如果我在控制台中运行一个简单的测试:
However, if I run a simple test as such in the console:
var test = [[1,2,3],7,8,9]; var shallow_copy = test.slice();并检查shallow_copy,我可以看到整个二维数组似乎被复制了。
and inspect shallow_copy, I can see that the entire 2 dimensional array appears to be copied over.
浅拷贝和深拷贝有什么区别?如果我猜的话,我会把它称为深层副本。
What is the difference between a shallow copy and a deep copy? If I were to guess, I would have called this a deep copy.
推荐答案要看到区别,请尝试:
shallow_copy[0][2] = 4; console.dir(test);你会看到 test 已经改性!这是因为虽然您可能已将值复制到新数组,但嵌套数组仍然是相同的。
You'll see that test has been modified! This is because while you may have copied the values to the new array, the nested array is still the same one.
深拷贝将递归执行浅拷贝,直到所有内容都是原件的新副本。
A deep copy would recursively perform shallow copies until everything is a new copy of the original.
更多推荐
浅拷贝和带有JavaScript数组的深拷贝有什么区别?
发布评论