210222 WECODE #8-1
Array.forEach()
- forEach는 for문 대신 사용할 수 있는 반복문
- 그러나 forEach는 아무것도 return하는 것이 없어서
- forEach로 전달되는 callback 함수에서도 return하는 것이 없다. (map과의 차이점!)
빈 배열에 해당하는 element 채우기
<script>
let emptyArray = [];
let names = ['a', 'ab', 'cbb', 'ada'];
names.forEach((el) => {
if (el.startsWith('a')) {
emptyArray.push(el);
}
});
console.log(emptyArray);
</script>
forEach에서 현재 index를 알고 싶으면 두 번째 인자로 받으면 된다
<script>
let findeIndex;
let arr = ['a', 'b', 'c', 'd'];
arr.forEach((el, idx) => {
if (el === 'c') {
findIndex = idx;
return;
}
});
console.log(findIndex);
</script>
forEach도 함수이므로, 중간에 반복문을 탈출하려면 return을 사용
<script>
let hasC = false;
let arr = ['a', 'b', 'c', 'd'];
arr.forEach(el => {
if (el === 'c') {
hasC = true;
return;
}
});
console.log(hasC);
arr.forEach(el => {
if (el === 'e') {
hasC = true;
return;
}
});
console.log(hasC);
</script>
Array.map()
- map 메서드는 배열을 반복
- callback 함수에서 return한 값으로 매(Each)요소들을 수정
- map 메서드의 return 값은 "새로운 배열"로 "return"
<script>
let arr = [1, 2, 3];
let squares = arr.map(function (x) {
return x * x;
})
console.log(squares);
</script>