Javascript slice方法是否返回浅层副本? [英] Does Javascript slice method return a shallow copy?

查看:159
本文介绍了Javascript slice方法是否返回浅层副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一位Mozilla开发者中,韩语lang说'slice method'返回一个新的数组。

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'更改animals数组, 'bison','aaa','duck','elephant']。

but, If slice method returns shallow array, the animals array should be changed with ['ant', 'bison', 'aaa', 'duck', 'elephant'].

为什么它是浅色副本?

Why is it shallow copy?

推荐答案

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:

对于对象引用(而不是实际对象),slice将对象引用复制到新数组中。原始数组和新数组都引用相同的对象。如果引用的对象发生更改,则更改对新的和原始数组都可见。

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.

对于字符串,数字和布尔值(不是String,Number和Boolean对象),slice将值复制到新数组中。对一个数组中的字符串,数字或布尔值的更改不会影响另一个数组。
如果将新元素添加到任一数组,则另一个数组不受影响。( source

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方法是否返回浅层副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆