JavaScript - 0~n Array 만들기

1 minute read

[0,1,2,...,n] 와 같은 배열을 만드는 방법 (ES6)

const arr1 = Array.from({length:n});
const arr2 = [...Array(n)].map((v,i)=>i); 
const arr3 = [...Array(n).keys()]; 
const arr4 = [...Array(n).keys()].map(i=>i+1); 

1.Array.from()

Array.from() 메소드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운 Array 객체를 만들어 리턴한다.

  • Array.from(arrayLike[, mapFn[, thisArg]])
    • arrayLike : 배열로 변환하고자 하는 유사 배열 객체나 반복 가능한 객체.
    • mapFn : 배열의 모든 요소에 대해 호출할 맵핑 함수.(Optional)
    • thisArg : mapFn 실행 시에 this로 사용할 값.(Optional)
    • return : 새로운 Array 인스턴스

유사 배열 객체란 ? length 속성과 인덱싱된 요소를 가진 객체. Array.from() 메소드가 유사 배열 객체를 인자로 받는다는 말은 다시 말하면, 유사 배열 객체를 Array.from() 메소드를 이용해서 Array로 변환할 수 있다고 생각할 수도 있겠다.

예제

Array.from('foo') // ['f','o','o']

Array.from(new Set([1,2,3])) // [1,2,3]

const m = new Map([['1','a'],['2','b']]) //Map(2) {"1" => "a", "2" => "b"}
Array.from(m) // [['1','a'],['2','b']]
Array.from(m.keys()) // ["1", "2"]
Array.from(m.values()) // ["a", "b"]

Array.from([1,2,3], x=>x+x) // [2,4,6], map 함수처럼 동작한다.
Array.from({length:3}, (v,i)=>i) // [0,1,2], 길이가 3인 배열을 만드는데 초기값이 'undefined' 이므로 v 값이 'undefined' 임에 주의해야하여 mapFn을 작성해야한다. 사용하지 않는 인자는 '_' 로 표기하기도 하더라!

//Sequence generator function (range)
const range = (start, stop, step) => Array.from({length:(stop-start)/step +1}, (_, i) => start + (i * step));
range(0,2,1) // [0,1,2]
range(1,10,2) // [1,3,5,7,9]
range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x)); //  ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

그리고 …

function f1() {
    return Array.from(arguments)
}  
const f2 = () => {return Array.from(arguments)} // error

MDN 에 arguments 객체를 이용하는 예제가 있는데, MDN 에 arguments 객체에 대한 설명을 보면 ES6 호환 코드 작성 시 되도록 Rest 파라미터를 사용해야한다고 나와있다.

arrow function에서는 arguments를 사용할 수 없다.

2.[…Array(n)]

console.log([...Array(3)]); //[ undefined, undefined, undefined ]
console.log(Array(3)); //[ <3 empty items> ]
console.log(new Array(3)); //[ <3 empty items> ]
console.log(typeof Array(3)); //object
console.log(Array(3) instanceof Array); //true

const arr2 = [...Array(3)].map((v,i)=>i); //[0,1,2]
const arr3 = [...Array(3).keys()]; //[0,1,2]
const arr4 = [...Array(3).keys()].map(i=>i+1); //[1,2,3]

new 없이 Array(n) 만으로 길이가 n인 Array 객체를 생성할 수 있나보다.

길이만 정해진 Array객체의 요소들의 초기값은 undefined 이며 map 함수를 이용해 index로 이루어진 배열을 만들어줄 수도 있고, Array를 Object로 바라보면 index들은 key값들이므로 Object.keys() 메소드를 이용해서 index로 이루어진 배열을 만들어줄 수도 있다.

Reference

  • https://hjcode.tistory.com/73
  • https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/from
  • https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/arguments