结合两个数组的"荏苒"时尚 - 的JavaScript [英] Combine two arrays in a "zipping" fashion - JavaScript
问题描述
所以,我一直在想的只是一些小事情的做法,我可以用JavaScript数组做。我遇到了两个数组在一个拉拉链时尚相结合的理念(arrayA [0],arrayB [0],arrayA [1],arrayB [1] ...)等等等等。在任何一个潜在的较长阵列留下将上涨到年底。
So, I've been thinking of just some little practice things that I could do with arrays in JavaScript. I came across the idea of combining two arrays in a "zipping" fashion (arrayA[0], arrayB[0], arrayA[1], arrayB[1]...) and so on and so forth. Anything left over in a potential longer array would be tacked onto the end.
我搜索计算器 - 原因,我问的是我目前在入门程序设计课程,所以我们真的不知道了一大堆的东西,我们可以用JavaScript做。希望看到与简单的方法,如果可能的!解决方案
I've searched stackoverflow - reason I'm asking is I'm currently in introductory programming courses, so we don't really know a whole lot of "things" we can do with JavaScript. Would like to see a solution with "simple" methods if possible!
我目前得到了交替的方式走,但我似乎无法得到固定该阵列的其余部分到最后的最后部分。
I've currently got the alternate fashion going, but I can't seem to get the last part of tacking the remaining parts of the array to the very end.
function alternatingMerge(array1, array2)
//this function will merge two different arrays in an alternating fashion
//i.e = array1[0], array2[0], array1[1], array2[1], array1[2], array2[2], ... , etc
{
var mergedArray;
var i; // while loop counter
var j; //
var k; //
var arrayLengths;
arrayLengths = array1.length + array2.length;
i = 0; //
j = 0; // ARRAY1 COUNTER
k = 0; // ARRAY2 COUNTER
mergedArray = new Array(arrayLengths);
//window.alert(mergedArray);
while (i < arrayLengths)
{
if (i%2 === 0)
{
mergedArray[i] = array2[j];
j = j + 1;
}
else
{
mergedArray[i] = array1[k];
k = k + 1;
}
i = i + 1;
}
return mergedArray;
}
我觉得这很简单的东西,但有些帮助将是AP preciated!
I feel like it's simple stuff but some help would be appreciated!
推荐答案
这个怎么样:
function mergeAlternating(array1, array2) {
var mergedArray = [];
for (var i = 0, len = Math.max(array1.length, array2.length); i < len; i++) {
if (i < array1.length) {
mergedArray.push(array1[i]);
}
if (i < array2.length) {
mergedArray.push(array2[i]);
}
}
return mergedArray;
}
这篇关于结合两个数组的&QUOT;荏苒&QUOT;时尚 - 的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!