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' ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP