Array.prototype.forEach
ex
const numbers = [1, 2, 3];
let pows = [];
// for 문으로 순회
for (let i = 0; i < numbers.length; i++) {
pows.push(numbers[i] ** 2);
}
console.log(pows); // [ 1, 4, 9 ]
pows = [];
// forEach 메소드로 순회
numbers.forEach(function (item) {
pows.push(item ** 2);
});
// ES6 화살표 함수
// numbers.forEach(item => pows.push(item ** 2)); 으로도 가능하다
console.log(pows); // [ 1, 4, 9 ]v
forEach 메소드는 원본 배열(this)을 변경하지 않는다. 하지만 콜백 함수는 원본 배열(this)을 변경할 수는 있다.
const numbers = [1, 2, 3, 4];
// 원본 배열을 직접 변경하려면 콜백 함수의 3번째 인자(this)를 사용한다.
numbers.forEach(function (item, index, self) {
self[index] = Math.pow(item, 2);
});
console.log(numbers); // [ 1, 4, 9, 16 ]