유사 배열 객체를 이터러블 배열로 변환하기 위해 Array.from() 메서드 또는 스프레드 연산자 (...)를 사용할 수 있습니다.
const arrayLike = {
0: 'A',
1: 'B',
2: 'C',
length: 3
};
const convertedArray = Array.from(arrayLike);
console.log(convertedArray); // ['A', 'B', 'C']
const arrayLike = {
0: 'A',
1: 'B',
2: 'C',
length: 3,
[Symbol.iterator]: function* () {
let index = 0;
while (index < this.length) {
yield this[index++];
}
}
};
const convertedArray = [...arrayLike];
console.log(convertedArray); // ['A', 'B', 'C']
Array.from() 메서드를 사용하면 쉽게 구현할 수 있지만, 스프레드 연산자의 경우 이터러블 프로토콜이 구현되어 있어야 합니다. 두 가지 방법 중 하나를 선택하여 유사 배열 객체를 이터러블 배열로 변환할 수 있습니다.