JavaScript에서 TypedArray 객체의 forEach() 메서드는 콜백 함수를 인수로 받아, 타입 배열(typed array)에 포함된 각 요소마다 해당 함수를 한 번씩 순서대로 실행합니다. 일반 Array의 forEach()와 동작 방식이 동일하며, 반복 작업을 간결하게 처리할 때 유용합니다.
문법(Syntax)
typedArray.forEach(callback)
콜백 함수에는 아래와 같은 세 가지 인수가 전달됩니다.
- element: 현재 처리 중인 배열의 요소 값
- index: 현재 요소의 인덱스
- array:
forEach()를 호출한 배열 객체 자신
예제(Example)
<html>
<head>
<title>JavaScript TypedArray forEach Method</title>
</head>
<body>
<script type="text/javascript">
var int32View = new Int32Array([21, 19, 65, 21, 14, 66, 87, 55]);
document.write("Contents of the typed array: " + int32View);
document.write("<br>");
document.write("Result: ");
function testResult(element, index, array) {
document.writeln(element + 100);
}
int32View.forEach(testResult);
</script>
</body>
</html>
실행 결과(Output)
Contents of the typed array: 21,19,65,21,14,66,87,55 Result: 121 119 165 121 114 166 187 155
동작 방식 설명
위 예제에서는 Int32Array에 저장된 8개의 정수 요소 각각에 대해 testResult 콜백 함수가 호출되며, 모든 요소에 100을 더한 값이 차례대로 출력됩니다. 참고로 forEach()는 원본 배열을 변경하지 않고, 항상 undefined를 반환한다는 점을 기억해 두면 좋습니다.