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' ]
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短