JavaScript 构造一个数组,元素从字符串中重复

javascriptweb developmentobject oriented programming更新于 2025/10/2 21:32:17

我们必须编写一个函数,创建一个数组,元素从字符串中重复,直到达到限制。假设有一个字符串"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'
]

相关文章


有用资源