一次處理兩個單詞將兩個字串連線起來 - 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP