(深)使用jQuery复制数组 [英] (Deep) copying an array using jQuery
问题描述
可能重复:
克隆JavaScript对象的最有效方法是什么?
我需要复制一个(有序的,非关联的)对象数组。我正在使用jQuery。我最初尝试
I need to copy an (ordered, not associative) array of objects. I'm using jQuery. I initially tried
jquery.extend({}, myArray)
但是,当然,这给了我一个对象,我需要一个数组(顺便说一下,真的很喜欢jquery.extend)。
but, naturally, this gives me back an object, where I need an array (really love jquery.extend, by the way).
那么,复制数组的最佳方法是什么?
So, what's the best way to copy an array?
推荐答案
由于Array.slice()不进行深度复制,因此不适合多维数组:
Since Array.slice() does not do deep copying, it is not suitable for multidimensional arrays:
var a =[[1], [2], [3]];
var b = a.slice();
b.shift().shift();
// a is now [[], [2], [3]]
请注意,尽管我上面使用了 shift()。shift()
,但这一点只是 b [0] [0]
包含指向 a [0] [0]
的指针,而不是值。
Note that although I've used shift().shift()
above, the point is just that b[0][0]
contains a pointer to a[0][0]
rather than a value.
同样删除(b [0] [0])
也会导致 a [0 ] [0]
要删除, b [0] [0] = 99
也会更改 a的值[ 0] [0]
到99。
Likewise delete(b[0][0])
also causes a[0][0]
to be deleted and b[0][0]=99
also changes the value of a[0][0]
to 99.
jQuery的 extend
方法 在将真值作为初始参数传递时执行深层复制:
jQuery's extend
method does perform a deep copy when a true value is passed as the initial argument:
var a =[[1], [2], [3]];
var b = $.extend(true, [], a);
b.shift().shift();
// a is still [[1], [2], [3]]
这篇关于(深)使用jQuery复制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!