JavaScript-유사배열 객체와 Array.from( )

hannah·2023년 8월 1일
0

JavaScript

목록 보기
51/121

유사배열

태그.children은 배열처럼 생긴 객체이다. {0: td, 1: td, 2: td, length:3 }과 같은 모양을 가진 객체로서 children[0], children[1], children.length 처럼 사용할 수 있어서 배열로 착각하기 쉽다. 이러한 객체를 유사 배열 객체(array-like object)라고 한다.

유사 배열 객체에 indexOf와 같이 배열에 사용할 수 있는 메서드를 사용하려면 Array.from 메서드로 유사 배열 객체를 진짜 배열로 바꾸면 된다.

const checkWinner = (target) => {
	const rowIndex = target.parentNode.rowIndex;
    const cellIndex = target.cellIndex;
    console.log(Array.from(target.parentNode.children));
    console.log(Array.from(target.parentNode.children).indexOf(target));
    // 세 칸 다 채워졌나?
    let hasWinner = false;
	.
    .
    .

0개의 댓글