我试图写一个合并两个排序数组a和b的函数。但是,当数组b为0时,它只显示数组a作为输出:
function mergeSortedArrays(a,b) {
var merged = [],
aElm = a[0],
bElm = b[0],
i = 1, //index for array a
j = 1; //index for array b
if (a.length == 0) {
return b;
}
if (b.length == 0) {
return a;
}
while (aElm || bElm) {
if ((aElm && !bElm) || aElm < bElm) { //problem is that it thinks that 0 == !bElm
merged.push(aElm);
aElm = a[i++];
} else {
merged.push(bElm);
bElm = b[j++];
}
}
return merged;
}
mergeSortedArrays([2,5,6,9], [0,1,2,3,29]) //outputs [2,5,6,9]
我理解问题是因为0是假的,所以在条件if(aElm && !bElm)
下,它只是不断地将aElm推入merged
。什么是更好的编写条件的方法,以便它将0识别为整数而不是不存在?
答案 0 :(得分:2)
什么是更好的编写条件的方法,以便它将0识别为整数而不是不存在?
编写条件的更好方法是不测试数组元素的存在,而是检查索引。
function mergeSortedArrays(a,b) {
var merged = [],
i = 0, //index for array a
j = 0; //index for array b
while (i < a.length || j < b.length) {
if (j == b.length || a[i] < b[j]) {
merged.push(a[i++]);
} else {
merged.push(b[j++]);
}
}
return merged;
}
答案 1 :(得分:1)
您可以明确检查undefined
值。
function mergeSortedArrays(a, b) {
var merged = [],
aElm = a[0],
bElm = b[0],
i = 1, //index for array a
j = 1; //index for array b
if (a.length == 0) {
return b;
}
if (b.length == 0) {
return a;
}
while (aElm !== undefined || bElm !== undefined) {
if ((aElm !== undefined && bElm === undefined) || aElm < bElm) {
merged.push(aElm);
aElm = a[i++];
} else {
merged.push(bElm);
bElm = b[j++];
}
}
return merged;
}
console.log(mergeSortedArrays([2, 5, 6, 9], [0, 1, 2, 3, 29]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
如果没有负数
,请> -1
作为(aElm >-1) && !(bElm>-1)
function mergeSortedArrays(a,b) {
var merged = [],
aElm = a[0],
bElm = b[0],
i = 1, //index for array a
j = 1; //index for array b
if (a.length == 0) {
return b;
}
if (b.length == 0) {
return a;
}
while ((aElm >-1) || (bElm>-1)) {
if (((aElm >-1) && !(bElm>-1)) || aElm < bElm) { //problem is that it thinks that 0 == !bElm
merged.push(aElm);
aElm = a[i++];
} else {
merged.push(bElm);
bElm = b[j++];
}
}
return merged;
}
var result = mergeSortedArrays([2,5,6,9], [0,1,2,3,29]) //outputs [2,5,6,9]
console.log(result);
&#13;
这个解决方案呢
var a = [2,5,6,9];
var b = [0,1,2,3,29];
a = a.concat(b);
a.sort(function(a, b){return a - b});
console.log(a);
&#13;