问题描述
在 Mozilla 开发人员翻译的韩语 lang 中说切片方法"返回一个新的浅复制数组.
In a Mozilla developer translated Korean lang says 'slice method' returns a new array copied shallowly.
所以我测试了我的代码.
so I tested my code.
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
var t = animals.slice(2,4);
console.log(t);
t[0] = 'aaa';
console.log(t);
console.log(animals);
但是,如果 slice 方法返回浅数组,则应该将动物数组更改为 ['ant', 'bison', 'aaa', 'duck', 'elephant'].
but, If slice method returns shallow array, the animals array should be changed with ['ant', 'bison', 'aaa', 'duck', 'elephant'].
为什么是浅拷贝?
推荐答案
slice
不会改变原始数组.它返回原始数组中元素的浅拷贝.
slice
does not alter the original array.It returns a shallow copy of elements from the original array.
将原始数组的元素复制到返回的数组中,如下所示:
Elements of the original array are copied into the returned array as follows:
对于对象引用(而不是实际对象),切片将对象引用复制到新数组中.原始数组和新数组都指向同一个对象.如果引用的对象发生更改,则更改对新数组和原始数组都可见.
For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
对于字符串、数字和布尔值(不是字符串、数字和布尔对象),切片将值复制到新数组中.对一个数组中的字符串、数字或布尔值的更改不会影响另一个数组.如果向任一数组添加新元素,则另一个数组不受影响.(来源)
For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array do not affect the other array.If a new element is added to either array, the other array is not affected.(source)
在您的情况下,数组由字符串组成,切片将返回复制到数组的新字符串,因此是浅拷贝.为了避免这种情况,请使用数组的对象形式.
In your case the the array consists of strings which on slice would return new strings copied to the array thus is a shallow copy.In order to avoid this use the object form of array.
这篇关于Javascript slice 方法是否返回浅拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!