Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- foreach
- 코딩게임
- includes
- TIL
- supertest
- dot notation
- nvm 설치
- Bracket Notation
- JavaScript Runtime
- 슈도코드
- 스프린트 리뷰
- package.json
- for in
- testbuilder
- immutable
- node 설치
- global scope
- 코드스테이츠 1일차
- npm 설치
- version control system
- HTML 태그 모음
- for of
- 코플릿
- Jest
- Splice
- local scope
- javascript 기초
- 2번째 페어
- 호이스팅
- indexof
Archives
- Today
- Total
Honey-Programming
forEach 메소드 본문
# forEach (주어진 함수를 배열 요소 각각에 대해 실행)
문법 : forEach(callback(currentvalue[, index [, array]])[, thisArg])
callback : 각 요소에 실행할 함수
- currentvalue : 요소 값(처리할 현재 요소)
- index : 처리할 현재 요소의 인덱스
- array : forEach( )를 호출한 배열
thisArg : callback 실행할 때 this 값
반환값 : undefined
- 기본적인 forEach 사용법
const arr = [0,1,2,3,4,5,6,7,8,9,10];
arr.forEach(function(element){
console.log(element); // 0 1 2 3 4 5 6 7 8 9 10
});
// 혹은 arrow(화살표) 함수 가능
arr.forEach(element => {
console.log(element)
});
// for문으로 작성
const forOfAnimals = ["lion", "tiger"];
for (let i=0; i<forOfAnimals.length; i++) { // 결과값은 같음
console.log(forOfAnimals[i]); // lion
} // tiger
// forEach문으로 작성
const forEachOfAnimals = ["lion", "tiger"];
forEachOfAnimals.forEach(function(animal){ // 결과값은 같음
console.log(animal); // lion
}); // tiger
var arr = ['가','나','다','라'];
arr.forEach(function(item,index,arr2){
console.log(item,index,arr2[index+1]); // 현재요소, 인덱스번호, 다음요소
})
// 가 0 나
// 나 1 다
// 다 2 라
// 라 3 undefined
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element); // a[index] = element 형식으로 반복
}
// 인덱스 2는 배열의 그 위치에 항목이 없기에 무시하고 건너띈다
[2, 5, , 9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[3] = 9
- forEach로 홀수 배열 만들기
: forEach는 return이 없다고한다.
그래서 callback 함수에 의해서 어떤 결과물을 보이고 싶다면 함수 밖의 변수를 사용해야 한다.
const arr = [0,1,2,3,4,5,6,7,8,9,10];
const oddArray = [];
arr.forEach(function(element){
if(element%2==1) {
oddArray.push(element);
}
});
console.log(oddArray); // [ 1, 3, 5, 7, 9 ]
'JAVASCRIPT' 카테고리의 다른 글
filter 메소드 (0) | 2020.07.23 |
---|---|
map 메소드 (0) | 2020.07.23 |
slice, splice, split 메소드 (0) | 2020.07.22 |
immutable vs mutable (0) | 2020.07.21 |
var, let, const 차이(비교) (0) | 2020.07.21 |
Comments