我有两个节点列表nl_first& nl_second。
这两个列表中的任何一个都可能比另一个更大。
视觉上,如果
nl_first = a,b,c,d,e
nl_second = x,y,z
我需要我的数组a,x,b,y,c,z,d,e
。
我怎样才能优雅地实现这一目标?
答案 0 :(得分:0)
var one = ['a', 'b', 'c', 'd', 'e'];
var two = ['x', 'y', 'z'];
var combined = [];
for (var i = 0; i < one.length; i++) {
combined.push(one[i]);
if (two[i]) {
combined.push(two[i]);
}
}
console.log(combined);
// ["a", "x", "b", "y", "c", "z", "d", "e"]
请记住,如果两个元素长于一个,则额外的两个元素不会在数组中结束。
答案 1 :(得分:0)
我的脏实现,:p
var nl_first = "a,b,c,d,e";
var nl_second = "1,2,3";
console.log(customJoin(nl_first, nl_second));
//a,1,b,2,c,3,d,e
var nl_first = "a,b,c,d,e";
var nl_second = "1,2,3,4,5";
console.log(customJoin(nl_first, nl_second));
//a,1,b,2,c,3,d,4,e,5
var nl_first = "a,b,c,d,e";
var nl_second = "1,2,3,4,5,6";
console.log(customJoin(nl_first, nl_second));
//a,1,b,2,c,3,d,4,e,5,6
function customJoin(first, second) {
if (first.length > second.length) {
var secondArray = second.split(',');
secondArray.reverse();
var result = first.replace(/,/g, function (text) {
var item = secondArray.pop();
return (item) ? text + item + text: text;
});
return result;
} else {
var firstArray = first.split(',');
firstArray.reverse();
second = ',' + second;
var result = second.replace(/,/g, function (text) {
var item = firstArray.pop();
return (item) ? text + item + text: text;
});
result = result.replace(/^,/, '');
return result;
}
}
答案 2 :(得分:0)
var a = ['a', 'b', 'c', 'd', 'e', 'f'];
var b = ['j', 'r', 'o', 't', 'a'];
function mergeArrays(a, b)
{
var c = [];
var len = a.length;
if (b.length > len) len = b.length;
for (var i = 0; i < len; i++)
{
if (i < a.length) c.push(a[i]);
if (i < b.length) c.push(b[i]);
}
alert(c);
}
$().ready(function ()
{
mergeArrays(a, b);
mergeArrays(b, a);
});