创建多维数组,而不是引用的副本 - 的JavaScript [英] Create copy of multi-dimensional array, not reference - JavaScript

查看:102
本文介绍了创建多维数组,而不是引用的副本 - 的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object\">What是克隆JavaScript对象?最有效的方式

这也被称为深度复制,我已经发现了一些文章。最近似乎这一个但它是jQuery的 - 我想做到这一点没有一个图书馆。

This is also referred to as "deep copying", which I've found some articles on. Closest seems to be this one but it's for jQuery - I'm trying to do this without a library.

我也看到了,在两个地方,它是可能做这样的事情:

I've also seen, in two places, that it's possible to do something like:

arr2 = JSON.decode(JSON.encode(arr1));

但是,这显然是低效的。它也可以循环并单独复制每个值,并通过所有的阵列复发。这似乎是累人的,效率低下以及。

But that's apparently inefficient. It's also possible to loop and copy each value individually, and recurs through all the arrays. That seems tiring and inefficient as well.

那么,什么是最有效的,非图书馆的方式来复制一个JavaScript多维数组 [A],[B],[C] ?我与非IE浏览器的方法,如果有必要完全满意。

So what's the most efficient, non-library way to copy a JavaScript multi-dimensional array [[a],[b],[c]]? I am completely happy with a "non-IE" method if necessary.

谢谢!

推荐答案

因为它听起来像你处理阵列深度的一些未知的水平数组,但你只需要在一个级别来对付他们在深任何给定的时间,那么这将是简单和快速使用 .slice()

Since it sounds like you're dealing with an Array of Arrays to some unknown level of depth, but you only need to deal with them at one level deep at any given time, then it's going to be simple and fast to use .slice().

var newArray = [];

for (var i = 0; i < currentArray.length; i++)
    newArray[i] = currentArray[i].slice();

或使用 .MAP()而不是循环:

var newArray = currentArray.map(function(arr) {
    return arr.slice();
});

所以这个遍历当前阵列,并建立嵌套数组的浅拷贝一个新的数组。然后,当你去深度的一个新的水平,你会做同样的事情。

So this iterates the current Array, and builds a new Array of shallow copies of the nested Arrays. Then when you go to the next level of depth, you'd do the same thing.

当然,如果有数组和其他数据的混合物,你要测试的是什么你切了。

Of course if there's a mixture of Arrays and other data, you'll want to test what it is before you slice.

这篇关于创建多维数组,而不是引用的副本 - 的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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