Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

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'
]