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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP