按值复制数组 [英] Copy array by value

查看:118
本文介绍了按值复制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将JavaScript中的数组复制到另一个数组时:

When copying an array in JavaScript to another array:

var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d');  //Now, arr1 = ['a','b','c','d']

我意识到 arr2 指的是与 arr1 相同的数组,而不是一个新的独立数组。如何复制数组以获得两个独立的数组?

I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?

推荐答案

使用此:

var newArray = oldArray.slice();

基本上, slice() 操作克隆数组并返回对一个新的阵列。另请注意:

Basically, the slice() operation clones the array and returns a reference to a new array. Also note that:

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

For references, strings and numbers (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.

字符串和数字等基元是不可变的,因此对字符串或数字的更改是不可能。

Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.

这篇关于按值复制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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