如何在javascript中交替合并两个字符串?

时间:2017-09-06 05:06:16

标签: javascript string merge

给定输入str1是" abc"而str2是" def"输出应该是adbecf 给定str1 =" ab"和str2 =" def"输出应为adbef

我的输出是:

合并(' ABC'' DEF') " adbecfNaN"

合并(' AB'' DEF') " 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;

}

10 个答案:

答案 0 :(得分:2)

你需要在循环条件中使用<而不是<=,因为数组索引是从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'));

答案 1 :(得分:1)

最短的方式,可能是最快的,是迭代字符串的最小长度,然后取两个字符串的其余部分。

&#13;
&#13;
function zip(a, b) {
    var i,
        l = Math.min(a.length, b.length),
        temp = '';

    for( i = 0; i < l; i++) {
        temp += a[i] + b[i];
    }
    return temp + a.slice(i) + b.slice(i);
}

console.log(zip('abc', '123')); // a1b2c3
console.log(zip('ab', '123'));  // a1b23
console.log(zip('abcd', '12')); // a1b2cd
&#13;
&#13;
&#13;

使用ES6,您可以将Array.from与内置映射器一起用于字母。

&#13;
&#13;
var a = "ab",
    b = "def",
    result = Array.from(a.length > b.length ? a : b, (_, i) => (a[i] || "") + (b[i] || ""))
                  .join('');

console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

ES6中的一行:选择较大的字符串,在其上配对并加入:

var a = "ab", b = "def"

Array.from(a.length > b.length ? a : b)
     .map((_, i) => (a[i] || "") + (b[i] || ""))
     .join() 

答案 3 :(得分:0)

JS bin链接 - https://jsbin.com/nihoxivoxa/edit?js,console

function merge (str1, str2) {

  var a = str1.split("");

  var b = str2.split("");
  
  var count = 0;
  
  var merged_string = "";
  //let's determine the loop counts, which depends on the smaller length of string
  
  a.length < b.length ? count = a.length: count = b.length;
  
  
  for( var i=0; i< count; i++){
    merged_string += a[i]+b[i];
    
  }
  
  // add remaining characters

    count < str1.length 
    ? merged_string += str1.substr(count, str1.length)
    : merged_string += str2.substr(count, str2.length)

  
  return merged_string;

 
}
console.log(merge('ab','xysfergtrhyhn'))

答案 4 :(得分:0)

function merge(s1, s2) {
  var result = "";
  for(var i=0; i<s1.length && i<s2.length; i++){
   result+=s1[i]+s2[i];
  }
 s1.length<s2.length?result+=s2.substr(s1.length):result+=s1.substr(s2.length)
 return result;
}
console.log(merge("abc","12345"));
console.log(merge("12345","abc"));

答案 5 :(得分:0)

如果将字符串转换为数组,则可以递归地将每个数组的第一个元素移到新数组上,然后继续直到两个数组中都没有元素,最后返回新数组。

&#13;
&#13;
const shift = (a, b) => a.length||b.length?[a.shift(), b.shift(), ...shift(a,b)]:[];

console.log(shift([...'acegik'],[...'bdfhjl']).join('')); // abcdefghijkl
console.log(shift([...'aceg'  ],[...'bdfhjl']).join('')); // abcdefghjl
console.log(shift([...'acegik'],[...'bdfh'  ]).join('')); // abcdefghik
&#13;
&#13;
&#13;

答案 6 :(得分:0)

一种简单的方法:迭代最长的字符串,输出当前索引处的字符组合,如果当前索引中不存在字符,则使用空字符串。

console.log(merge('ab','def'));

function merge(a, b){
  for(var i = 0, s = '', l = Math.max(a.length, b.length); i < l; i++){
    s += a.charAt(i) || '';
    s += b.charAt(i) || '';
  }
  return s;
}

答案 7 :(得分:0)

使用ES6中的Lodash,可以用一个行代码解决此问题:

_.zip('abc'.split(''), 'def'.split('')).reduce((prev, curr) => prev + curr.join(''), '');

这里,zip函数由名为Lodash的节点库提供,可以从npm安装:https://lodash.com/

答案 8 :(得分:0)

这是一个小功能,它将分解两个字符串以产生与您描述的相同交替顺序的字符数组。然后,您可以使用join('')将这些字符组合成一个字符串。

var m = (a, b) => a.length ? [a[0], ...m(b, a.slice(1))] : b;
var string1 = "SCE ESG!";
var string2 = "ERTMSAE";
var mix = m(string1, string2);

console.log(mix.join(''));

或者如果您需要它来处理任意数量的输入字符串:

    var m = (a = [], ...b) => 
        b.length ? a.length ? [a[0], ...m(...b, a.slice(1))] : m(...b) : a;
    var string1 = "SR SG";
    var string2 = "EEMSE";
    var string3 = "CTEA!";
    var mix = m(string1, string2, string3);

    console.log(mix.join(''));

答案 9 :(得分:0)

const merge = (str1, str2) => str1.length && `${str1[0]}${merge(str2, str1.slice(1))}` || str2;

console.log(merge('abc','def'));
console.log(merge('ab','def'));