React
[java script]유사 배열과 배열의 차이
성장을꿈꾸는블루
2022. 7. 22. 16:28
배열(Array)이란?
하나의 변수명 아래에 데이터 아이템의 리스트를 저장하는 간편한 방법.
예시
var shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
shopping[0] = 'tahini';
shopping;
// shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
유사 배열 객체는
배열처럼 보이지만 사실 key가 숫자이고 length 값을 가지고 있는 객체를 말한다.
JS에서 querySelectorALL이나 document.body.children 유사 배열 객체에 담겨서 온다.
유사배열은 쉽게 말해서 []로 감싸져있지만 배열이 아닌 것!
유사배열 예시
var yoosa = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};
JavaScript
const texts = document.querySelectorAll('.text');
console.log(texts);
배열과 유사배열 둘의 차이
유사 배열과 배열의 차이점은 객체에 length 프로퍼티와 프로퍼티 이름이
숫자 0으로 시작하는 프로퍼티가 있다면 유사 배열입니다.
Argument 객체와 DOM에서 요소를 가져올 때 NodeList의 경우도 유사 배열 객체입니다.
Array.prototype 메서드 사용하기
유사 배열 객체는 Array 프로토타입에 메서드를 사용할 수 없습니다. 따라서 Array에 프로토타입에 있는 메서드를 사용하려면 call 메서드를 통해 호출을 할 수 있습니다.
출처: https://bearcomputer.tistory.com/35 [파란곰팅이의 컴퓨터마을:티스토리]
let a = ["red", "green", "blue"];
let b = {
0: "red",
1: "green",
2: "blue",
length: 3
};
Array.prototype.push.call(b,"white");
console.log(b); // -> {0: 'red', 1: 'green', 2: 'blue', 3: 'white', length: 4}
Array.prototype.forEach.call(b,(value) => console.log(value));
// red
// green
// blue
// white
출처: https://bearcomputer.tistory.com/35 [파란곰팅이의 컴퓨터마을:티스토리]