JavaScript 用帶有重複元素的字串構造一個數組


我們必須編寫一個函式,該函式使用字串中的元素建立一個數組,直到達到限制。假設有一個字串“aba”和限制 5 −

string = "aba" and limit = 5 will give new array ["a","b","a","a","b"]

讓我們編寫此函式的程式碼 −

示例

const string = 'Hello';
const limit = 15;
const createStringArray = (string, limit) => {
   const arr = [];
   for(let i = 0; i < limit; i++){
      const index = i % string.length;
      arr.push(string[index]);
   };
   return arr;
};
console.log(createStringArray(string, limit));
console.log(createStringArray('California', 5));
console.log(createStringArray('California', 25));

輸出

控制檯中的輸出將為 −

[
   'H', 'e', 'l', 'l',
   'o', 'H', 'e', 'l',
   'l', 'o', 'H', 'e',
   'l', 'l', 'o'
]
[ 'C', 'a', 'l', 'i', 'f' ]
[
   'C', 'a', 'l', 'i', 'f', 'o',
   'r', 'n', 'i', 'a', 'C', 'a',
   'l', 'i', 'f', 'o', 'r', 'n',
   'i', 'a', 'C', 'a', 'l', 'i',
   'f'
]

更新時間:2020 年 8 月 24 日

132 次瀏覽

開始你的 職業生涯

完成該課程即可獲得認證

開始
廣告
© . All rights reserved.