在JavaScript值数组复制 [英] Copying array by value in JavaScript

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

问题描述

当复制在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 ,而不是一个新的,独立的数组。我怎样才能复制数组以得到两个独立的阵列?使用jQuery将是巨大的。

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? Using jQuery would be great.

推荐答案

使用这样的:

var newArray = oldArray.slice();

基本上,<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\">slice()操作克隆阵列并返回参照新的阵列。还要注意的是:

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


  • 对于对象引用(而不是实际的对象),片拷贝对象引用到新的数组。原始和新数组指代相同的对象。如果引用的对象改变,这些改变是两个新的和原有的阵列可见。

  • 对于字符串和数字,片拷贝字符串和数字到新阵列。改变在一个阵列的字符串或数字,不影响其它阵列。

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

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