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

查看:21
本文介绍了创建多维数组的副本,而不是引用 - 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() 而不是 for 循环:

Or using .map() instead of the for loop:

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天全站免登陆