유사 배열 Array-Like

Park, Jinyong·2020년 4월 6일
0

Small, but Valuable.

목록 보기
3/19

length 속성과 인덱싱(0, 1, 2, ...)된 요소를 가진 객체

유사 배열은 배열처럼 length 속성을 지니고 index 번호가 0부터 시작하여 1씩 증가하는 객체이다. 배열이 아니라서 배열 메소드를 사용할 수 없다. Symbol.iterator가 없으므로 for...of 문에서도 에러가 발생한다.

let arrayLike = {
  0: 'This',
  1: 'is',
  2: 'not',
  3: 'an',
  4: 'array.',
  length: 5
}
console.log(Array.isArray(arrayLike)); // false
console.log(arrayLike instanceof Array); // false

arrayLike.push('newItem'); // TypeError: arrayLike.push is not a function

for (const e of arrayLike) {
    console.log(e);
} // Uncaught TypeError: arrayLike is not iterable

Array.from()을 이용해서 유사 배열 객체를 복사해 새로운 배열 객체로 만들 수 있다.

let arrayFromAL = Array.from(arrayLike);

console.log(Array.isArray(arrayFromAL)); // true
console.log(arrayFromAL instanceof Array); // true

arrayFromAL.push('newItem');
arrayFromAL[2] = 'now';

for (const e of arrayFromAL) {
  process.stdout.write(e + ' '); // process.stdout.write()는 Node의 한 기능으로 `console.log()`과 달리 줄바꿈을 하지 않는다.
}

// true
// true
// This is now an array. newItem

이제 배열로서 제어할 수 있다. 하지만 복사한 배열 값을 변경해도 기존의 arrayLike는 변경되지 않는다.

0개의 댓글