Array.from(arrayLike[, mapFn[, thisArg]])
매개변수
- arrayLike
배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체.- mapFnOptional
배열의 모든 요소에 대해 호출할 맵핑 함수.- thisArgOptional
mapFn 실행 시에 this로 사용할 값.
반환 값
새로운 Array 인스턴스
//for문을 활용한 배열
const arr = [];
for (let i = 1; i <= 31; i++) {
arr.push(i);
}
console.log(arr);
//array를 활용한 배열
const arr = Array.from(Array(31), (index) => index + 1);
console.log(arr);
//첫번째 인자로{length:__}를 넣어주고, 두번째 인자로는 index만 반환
const arr = Array.from({length:5}, (_,i) => i); // [0,1,2,3,4]
const testNum = 2
const arr = Array.from({length:4}, (_,i) => i + testNum); //[2,3,4,5]
//기존 배열을 가공한 새 배열을 만들때
//첫번째 인자로 기존배열을 넣고, 두번째 인자로 x
//배열[1,2,3]을 기반으로 원소를 하나씩 검사해 새 배열을 만든다
const arr = Array.from([1,2,3], x => x + x); //[2,4,6]
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]