一次将两个字符串与两个单词连接在一起-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
热门推荐
2 训练狗狗成为
3 训练狗狗几岁
4 反应训练狗狗
5 听力训练狗狗
7 狗狗尿训练
8 拳击训练狗狗
10 狗狗训练卧室
11 一个月狗狗怎么训练
12 几个月训练狗狗大小便
13 牧羊犬训练狗狗
14 狗狗训练做
15 狗狗训练它
16 可以训练狗狗
17 训练狗狗给球
18 训练狗狗的技巧