프론트/JavaScript
JS) Array.from() 함수 사용법 / 문자열을 문자열 배열로 변환(문자배열)
뽀짝코딩
2025. 1. 12. 23:25
728x90
Array.from()은 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 배열로 변환하는 데 사용.
문법
Array.from(arrayLike, mapFunction, thisArg);
매개변수
- arrayLike: 배열로 변환하려는 유사 배열 객체 또는 반복 가능한 객체.
- mapFunction (선택 사항): 배열의 각 요소에 대해 호출할 매핑 함수.
- thisArg (선택 사항): mapFunction을 실행할 때 this로 사용할 값.
사용 예제
1. 유사 배열 객체를 배열로 변환 (문자열 => 문자배열)
let str = "Hello";
let arr = Array.from(str);
console.log(arr); // ["H", "e", "l", "l", "o"]
2. mapFunction 사용
mapFunction을 통해 각 요소를 변환하면서 배열 생성:
let nums = Array.from([1, 2, 3, 4], x => x * 2);
console.log(nums); // [2, 4, 6, 8]
3. thisArg 사용
thisArg를 통해 mapFunction 내부에서 this를 설정:
let multiplier = { factor: 3 };
let nums = Array.from([1, 2, 3], function (x) {
return x * this.factor;
}, multiplier);
console.log(nums); // [3, 6, 9]
4. 반복 가능한 객체 변환 (set객체 => 배열)
Set은 유일한 값을 저장하는 특수한 자료구조, 중복되는 배열로 변환하는 것.
let set = new Set([1, 2, 3]);
let arr = Array.from(set);
console.log(arr); // [1, 2, 3]
5. 유사 배열 객체 변환
DOM 컬렉션이나 arguments 객체를 배열로 변환:
function example() {
let argsArray = Array.from(arguments);
console.log(argsArray);
}
example(1, 2, 3); // [1, 2, 3]
6. 숫자 범위 배열 생성
let range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range); // [1, 2, 3, 4, 5]
주요 특징
- 배열 생성:
- Array.from()은 배열이 아닌 객체를 쉽게 배열로 변환.
- 유사 배열 객체 및 반복 가능한 객체를 다룰 때 매우 유용.
- 맵핑과 동시에 변환:
- mapFunction을 통해 배열 생성 중 동시에 요소를 변환할 수 있다.
Array.from()과 Array.prototype.map()의 차이
Array.from()은 배열 생성 시 동시에 변환할 수 있지만, map()은 기존 배열에서 변환된 배열을 반환.
// Array.from()
let nums = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(nums); // [1, 2, 3, 4, 5]
// map()
let original = [1, 2, 3];
let doubled = original.map(x => x * 2);
console.log(doubled); // [2, 4, 6]
Array.from()은 배열이 아닌 것을 다룰 때 더 적합
참고 쳇지피티
반응형