给定输入str1为“abc”且str2为“def”输出应为adbecf
给定str1 =“ab”和str2 =“def”输出应为adbef
我的输出是:
合并( ‘ABC’,‘高清’)
“adbecfNaN”
合并( ‘AB’,‘高清’)
“adbeundefinedf”
我一直试图过滤undefined和NAN,但它不起作用.
这是我的代码:
function merge (str1,str2) {
var a = str1.split("").filter(Boolean);
var b = str2.split("");
var mergedString = '';
for(var i = 0; i <= a.length && i <= b.length; i++) {
mergedString += a[i] + b[i];
}
return mergedString;
}
最佳答案
你需要使用<而不是< =在循环条件下,因为数组索引从0开始.这就是你得到NaN的原因.你可以这样做:
function merge (str1,str2) {
var a = str1.split("").filter(Boolean);
var b = str2.split("");
var mergedString = '';
for(var i = 0; i < a.length || i < b.length; i++) { //loop condition checks if i is less than a.length or b.length
if(i < a.length) //if i is less than a.length add a[i] to string first.
mergedString += a[i];
if(i < b.length) //if i is less than b.length add b[i] to string.
mergedString += b[i];
}
return mergedString;
}
console.log(merge('abc','def'));
console.log(merge('ab','def'));