배열 반복문 정리
Apr 11, 2021
»
JavaScript
forEach()
각각의 배열 요소에 순환을 돌며 콜백함수를 호출합니다
[2, 6, 7].forEach(function (element, index, array) {
console.log(index + element);
});
// 02
// 16
// 27
map()
처리하고 새로운 배열 작성
index, array은 생략 가능
let square = [1, 2, 3, 4, 5].map(function (element, index, array) {
return element * element;
});
console.log(square); // [1,4,9,16,25];
filter()
조건에 일치하는 것만 추출
index, array는 생략 가능
let filtered = [16, 3, 3, 111, 78].filter(function(element, index, array)) {
return (element >= 11);
});
console.log(filtered); // [ 16, 111, 78 ]
reduce()
로직을 처리후 하나의 값을 취득
let total = [0,1,2,3],reduce(function(previousValue, currentValue, index, array) {
return previousValue + currentValue;
});
console.log(total); // 6
reduceRight() 얘는 reduce랑 같지만 오른쪽부터 처리