저장을 습관화

자바스크립트 Array를 이용하여 정수 n부터 m까지의 배열을 만드는 방법 본문

공부/JavaScript

자바스크립트 Array를 이용하여 정수 n부터 m까지의 배열을 만드는 방법

ctrs 2023. 9. 21. 22:38

개념

let n = 10;

console.log(Array(n)); // [ <10 empty items> ]

console.log(Array(n).fill()); // [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined  ]

console.log(Array(n).fill().map((_, i) => i + 1)); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

 

1. 새로운 배열을 생성하는 Array() 함수를 사용, n개의 빈 요소를 가진 배열을 생성

 

2. fill() 함수를 사용, 각 요소를 '정의되지 않음' 상태로 만듦

 

3. map() 함수를 사용, '현재 요소는 사용하지 않으며, 각 요소에 index + 1을 저장한다.'고 선언

 

 

응용

// 1부터 10으로 이루어진 정수 배열을 만든다고 할 때

let i = 1
let j = 10

console.log(Array()) // []

console.log(Array(j - i)) // [ <9 empty items> ]

console.log(Array(j - i).fill(i)) // [ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]

console.log(Array(j - i).fill(i).map((v, i) => v + i) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

console.log(Array(j - i + 1).fill(i).map((v, i) => v + i) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]