在字串中使用 JavaScript 重複每個字元與其基於 1 索引 number 的次數


問題

我們要求寫一個 JavaScript 函式,它接收一個英文小寫字母字串。

我們的函式應構造一個新字串,其中每個字元都與它們在字串中基於 1 的索引重複相同次數的大寫形式,並且不同的字元集應由連字元“-”分隔。

因此,字串“abcd”應變為 −

"A-Bb-Ccc-Dddd"

示例

以下為程式碼 −

 即時演示

const str = 'abcd';
const repeatStrings = (str) => {
   const res = [];
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      let temp = el.repeat(i + 1);
      temp = temp[0].toUpperCase() + temp.substring(1, temp.length);
      res.push(temp);
   };
   return res.join('-');
};
console.log(repeatStrings(str));

輸出

A-Bb-Ccc-Dddd

更新於: 20-Apr-2021

468 次檢視

啟動你的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.