PracticeEveryday
유사배열 vs 배열 본문
유사 배열 vs 배열
- JavaScript의 유사 객체 배열은 배열처럼 보이지만 사실 key가 숫자이고 length 값을 가지고 있는 객체를 의미한다.
// 유사 배열
const similarArray = {
0: "zero",
1: "one",
2: "two",
length: 3,
};
console.log(similarArray);
// { '0': 'zero', '1': 'one', '2': 'two', '3': 'three', length: 3 }
console.log(similarArray.length);
// 3
// 배열
const arrr = [1, 2, 3];
console.log(arr);
// [1, 2, 3]
console.log(arr.length);
// 3
- 배열같이 생겼지만 사실 객체다. ==> 유사 배열 객체
이 유사 배열 객체의 경우 forEach, map, filter, reduce 같은 배열 메서드를 사용 할 수 없다.
- 사용 하고 싶다면 Array.from () 메서드를 통해 배열로 만들어 주는 것이다.
Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해새로운Array 객체를 만듭니다.(MDN)
const similarArray = {
0: 1,
1: 2,
2: 3,
length: 3,
};
console.log(similarArray.__proto__ === Object.prototype);
// true
arr2 = Array.from(similarArray);
console.log(arr2); // [1, 2, 3]
console.log(arr2.__proto__ === Array.prototype);
// true
arr2.forEach((item) => console.log(item * 2)); //2, 4, 6
- 배열 메서드 사용 가능!!
※ JS에서 querySelectorAll이나 document.body.children으로 엘리먼트를 가져오면 유사 배열 객체에 담겨서 온다고 한다.
유사 배열 객체와 배열의 차이
유사 객체 배열(array-like objects)란 무엇이고 배열과 어떤 차이가 있는지 간단하게 알아보겠다.유사 객체 배열은 배열처럼 보이지만 사실 key가 숫자이고 length 값을 가지고 있는 객체를 말한다. JS
velog.io
'정리 > Question' 카테고리의 다른 글
3rd Party (0) | 2022.06.04 |
---|---|
이터레이터 vs 배열 (0) | 2022.06.02 |
Internet vs WWW ( World Wide Web ) (0) | 2022.05.30 |
Method vs Function (0) | 2022.05.19 |
수학의 함수와 프로그래밍의 함수 (0) | 2022.05.19 |
Comments