728x90
반응형
Array.from()은 JavaScript에서 **유사 배열 객체(array-like object)**나 **
반복 가능한 객체(iterable object)**를 배열로 변환하는 데 사용되는 메서드입니다.
Array.from(arrayLike, mapFunction, thisArg)
- arrayLike: 변환하려는 유사 배열 객체나 반복 가능한 객체입니다. 예를 들어, 문자열, Set, Map, NodeList 등이 될 수 있습니다.
- mapFunction (선택적): 배열로 변환된 후 각 요소에 대해 실행할 함수입니다.
- thisArg (선택적): mapFunction에서 this로 사용될 값입니다.
주요 특징:
- 유사 배열 객체 변환: 배열처럼 인덱스를 가지지만 배열 메서드를 가지지 않는 객체를 배열로 변환합니다.
- 반복 가능한 객체 변환: Set, Map, 문자열과 같은 반복 가능한 객체를 배열로 변환합니다.
예시 1: 유사 배열 객체 변환
let str = "Hello";
let arr = Array.from(str);
console.log(arr); // ['H', 'e', 'l', 'l', 'o']
예시 2: Set을 배열로 변환
let set = new Set([1, 2, 3, 4, 5, 5]);
let arr = Array.from(set);
console.log(arr); // [1, 2, 3, 4, 5]
예시 3: mapFunction을 사용하여 배열 변환
let arr = Array.from([1, 2, 3], x => x * 2);
console.log(arr); // [2, 4, 6]
예시 4: thisArg 사용
function MyClass() {
this.value = 10;
}
let arr = Array.from([1, 2, 3], function(x) {
return x + this.value;
}, new MyClass());
console.log(arr); // [11, 12, 13]
thisArg를 사용하면 mapFunction에서 this를 지정할 수 있습니다.
위 예제에서는 MyClass 객체의 value 값을 더한 결과를 배열로 반환합니다.
728x90
반응형
'Front > JS & jQuery' 카테고리의 다른 글
[js/jQuery] jQuery와 JavaScript의 .map() 차이 (0) | 2025.01.13 |
---|---|
[js] .reduce() 그룹화 (0) | 2025.01.11 |
[js/jQuery] each 와 for 루프 비교 2 (0) | 2025.01.09 |
[js] match (0) | 2025.01.06 |
[js] include / some (0) | 2025.01.05 |