[자바스크립트] Array.from() - 배열 초기화 한번에 하기

정말 간단한 한줄짜리 코드이다.

일일히 반복문을 돌리며 초기화를 했는데,

이 방법을 사용하면 그렇게 할 필요가 없다!

 

자바스크립트 Array 객체에는 Array.from() 이라는 함수가 존재하는데

길이 객체와 값을 반환하는 콜백함수를 매개변수로 넘겨주면 된다.

let answer = Array.from({length:5}, ()=>1);
console.log(answer); // 결과 : [1, 1, 1, 1, 1]

answer = Array.from({length:5}, (v, i)=> i);
console.log(answer); // 결과 : [0, 1, 2, 3, 4]

 

Array.from() 함수의 특징은 얕은 복사(shallow-copied) 된 새로운 객체를 생성한다는 것이다.

 

 

Array.from() - JavaScript | MDN

Array.from() The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive example

developer.mozilla.org

 

320x100