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

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

问题描述

在 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?

推荐答案

使用这个:

let oldArray = [1, 2, 3, 4, 5];

let newArray = oldArray.slice();

console.log({newArray});

基本上,slice() 操作克隆数组并返回对新数组的引用.

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

对于引用、字符串和数字(​​而不是实际对象),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天全站免登陆