JavaScript 中的两个字符串的两次连接


我们需要编写一个 JavaScript 函数,该函数接受两个字符串;创建一个新字符串,其中包含第一个字符串的前两个单词、第二个字符串的接下来的两个单词,然后再是第一个,然后是第二个,依此类推。

例如:如果字符串是 −

const str1 = 'Hello world';
const str2 = 'How are you btw';

则输出应为 −

const output = 'HeHollw o arwoe rlyodu btw';

因此,让我们编写此函数的代码 −

示例

此代码为 −

const str1 = 'Hello world';
const str2 = 'How are you btw';
const twiceJoin = (str1 = '', str2 = '') => {
   let res = '', i = 0, j = 0, temp = '';
   for(let ind = 0; i < str1.length; ind++){
      if(ind % 2 === 0){
         temp = (str1[i] || '') + (str1[i+1] || '')
         res += temp;
         i += 2;
      }else{
         temp = (str2[j] || '') + (str2[j+1] || '')
         res += temp;
         j += 2;
      }
   };
   while(j < str2.length){
      res += str2[j++];
   };
   return res;
};
console.log(twiceJoin(str1, str2));

输出

控制台中的输出为 −

HeHollw o arwoe rlyodu btw

更新日期: 2020-10-19

105 次浏览

开启你的 职业生涯

完成课程以获得认证

开始学习
广告
© . All rights reserved.