TypedArray.entries()란?
entries() 메서드는 해당 TypedArray 객체를 순회할 수 있는 이터레이터(iterator)를 반환합니다. 이 이터레이터를 사용하면 배열의 키-값 쌍을 가져올 수 있으며, 여기서 키는 배열의 인덱스, 값은 해당 인덱스에 저장된 요소입니다. 즉, 일반 배열의 Array.prototype.entries()와 동일한 방식으로 동작합니다.
구문
사용 구문은 다음과 같습니다.
typedArray.entries()
별도의 매개변수는 받지 않으며, 호출된 TypedArray 자신을 순회하는 이터레이터 객체를 반환합니다.
예제 1: 기본 사용법
다음 예제에서는 Int32Array를 생성한 뒤, entries()가 반환한 이터레이터를 next() 메서드로 순회하며 각 인덱스와 요소의 쌍을 출력합니다.
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var int32View = new Int32Array([21, 64, 89, 65, 33, 66, 87, 55]);
document.write("Contents of the typed array: " + int32View);
document.write("<br>");
var it = int32View.entries();
for(i=0; i<int32View.length; i++) {
document.write(it.next().value);
document.write("<br>");
}
</script>
</body>
</html>실행 결과
Contents of the typed array: 21,64,89,65,33,66,87,55 0,21 1,64 2,89 3,65 4,33 5,66 6,87 7,55
출력 결과를 보면 각 줄마다 “인덱스,요소” 형태의 쌍이 순서대로 출력되는 것을 확인할 수 있습니다.
예제 2: 이터레이터가 끝난 후 next() 호출하기
이터레이터가 이미 배열의 마지막 요소를 지나쳤는데도 next()를 계속 호출하면 더 이상 반환할 값이 없으므로 undefined가 결과로 나타납니다.
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var int32View = new Int32Array([21, 64, 89, 65, 33, 66, 87, 55]);
document.write("Contents of the typed array: " + int32View);
document.write("<br>");
var it = int32View.entries();
for(i=0; i<int32View.length; i++) {
document.write(it.next().value);
document.write("<br>");
}
document.write(it.next().value);
</script>
</body>
</html>실행 결과
Contents of the typed array: 21,64,89,65,33,66,87,55 0,21 1,64 2,89 3,65 4,33 5,66 6,87 7,55 undefined
참고: for...of 문으로 더 간결하게 순회하기
실무에서는 next()를 직접 호출하는 대신 for...of 문을 사용하는 것이 더 안전하고 가독성이 좋습니다. 이터레이터가 자동으로 종료되므로 위와 같은 undefined 문제도 발생하지 않습니다.
const int32View = new Int32Array([21, 64, 89, 65, 33, 66, 87, 55]);
for (const [index, value] of int32View.entries()) {
console.log(index, value);
}