本文介绍了在jQuery中以交替顺序合并两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组A
和B
,它们都包含许多元素,看起来像这样:
I have two arrays A
and B
, both of which contain lots of elemets and look like this:
var A = ["A", "B", "C", "D"];
var B = [1, 2, 3, 4];
现在我想要一个数组C
,它通过以交替的顺序将它们串联",从而合并" A
和B
Now I want an array C
that "merges" A
and B
by concatenating them in alternating sequence so that
C = ["A", 1, "B", 2, "C", 3, "D", 4]
我尝试过:
for (var i = 0; p < 3; i++) {
C = A[i].concat(B[i])
}
但这会导致C = "D4"
.
如何通过交替选择每个数组的一个元素来实现合并两个数组?
How can I achieve that I merge two arrays in by alternately choosing one element of each array?
推荐答案
var l = A.length + B.length,
C = Array(l);
for(var i=0; i<l; ++i)
C[i] = (i%2 ? B : A)[i/2|0];
基本上,它会根据i
是偶数还是奇数,用A
或B
中的项目填充C
.
Basically, it fills C
with items from A
or B
depending on if i
is even or odd.
请注意,我使用i/2|0
作为快捷方式,但仅在l
严格小于2 时才可以使用.为了安全起见,请使用Math.floor(i/2)
.
Note I used i/2|0
as a shortcut, but it will only work i l
is strictly less than 2. If you want to be safe, use Math.floor(i/2)
.
这篇关于在jQuery中以交替顺序合并两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!