如何連線 JavaScript 的字串陣列


我們需要編寫一個 JavaScript 函式,該函式接受一個字串陣列。此函式應連線陣列中的所有字串,將所有空格替換為“-”,並返回由此形成的字串。

例如:如果陣列是 -

const arr = ["QA testing promotion ", " Twitter  ", "Facebook ", "Test"];

輸出應為 -

const output = "QA-testing-promotion-Twitter-Facebook-Test";

示例

程式碼如下 -

const arr = ["QA testing promotion ", " Twitter ", "Facebook ", "Test"];
const joinArr = arr => {
   const arrStr = arr.join('');
   let res = '';
   for(let i = 0; i < arrStr.length; i++){
      if(arrStr[i] === ' '){
         if(arrStr[i-1] && arrStr[i-1] !== ' '){
            res += '-';
         };
         continue;
      }else{
         res += arrStr[i];
      };
   };
   return res;
};
console.log(joinArr(arr));

輸出

這將在控制檯上產生以下輸出 -

QA-testing-promotion-Twitter-Facebook-Test

更新於: 2020 年 10 月 1 日

98 次瀏覽

開啟您的 職場生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.