使用 JavaScript 中的 for 迴圈,用特定字元連線陣列的每個元素


我們假定編寫一個函式,它接收兩個引數,第一個引數是 String 或 Number 字面量的陣列,第二個引數是 String,並且我們必須返回一個字串,其中包含陣列的所有元素,這些元素由字串前置和後置。

例如,−

applyText([1,2,3,4], ‘a’);

應返回“a1a2a3a4a”

對於這些要求,與 for 迴圈相比,陣列 map() 方法是一個更好的選擇,這樣做的程式碼如下:

示例

const numbers = [1, 2, 3, 4];
const word = 'a';
const applyText = (arr, text) => {
   const appliedString = arr.map(element => {
      return `${text}${element}`;
   }).join("");
   return appliedString + text;
};
console.log(applyText(numbers, word));

輸出

此程式碼的控制檯輸出為 −

a1a2a3a4a

更新於:2020 年 8 月 18 日

232 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告