MDN_Array.prototype.forEach() >
forEach()
- ๋ฐฐ์ด์ ์๋ ๊ฐ ์์์ ๋ํด ํ๋์ฉ ์ฝ์ด ๊ฐ๋ฉด์ ์ฝ๋ฐฑ ํจ์๋ฅผ ํธ์ถํ๋ค.
- ์ญ์ ํ๊ฑฐ๋ ์ด๊ธฐํํ์ง ์์ ์ธ๋ฑ์ค ์์ฑ์ ๋ํด์๋ ์คํํ์ง ์๋๋ค.
- ์ฝ๋ฐฑ ํจ์ ํ๋ผ๋ฏธํฐ : ์๋ฆฌ๋จผํธ ๊ฐ, ์ธ๋ฑ์ค, ๋ฐฐ์ด ์ ์ฒด
let list = ["A", "B", "C"];
list.forEach(function(el, index, all){
log(el + ":" + index + ":" + all);
});
//A:0:A,B,C
//B:0:A,B,C
//C:0:A,B,C
- ์ฝ๋ฐฑ ํจ์๋ฅผ ๋ถ๋ฆฌํ ์ ์์ด ๋ ๋ฆฝ์ฑ์ด ์ข์์ง๋ค.
var list = ["A", "B", "C"];
var list2 = ["D", "F", "G"];
var fn = function(el, index, all){
log(el + ":" + index + ":" + all);
};
list.forEach(fn)
//A:0:A,B,C
//B:0:A,B,C
//C:0:A,B,C
list2.forEach(fn)
//D:0:D,F,G
//F:0:D,F,G
//G:0:D,F,G
- this๋ก ์ค๋ธ์ ํธ๋ฅผ ์ฐธ์กฐํ ์ ์๋ค.
var list = ["1", "2"];
var fn = function(el, index, all){
log(el + this.ten);
};
list.forEach(fn, {tne : 10});
forEach()์ ๋ฐ๋ณต ๋ฒ์
- forEach()๋ฅผ ์์ํ ๋ ๋ฐ๋ณต ๋ฒ์๊ฐ ๊ฒฐ์ ๋์ด, ๋์ค์ ์๋ฆฌ๋จผํธ๋ฅผ ์ถ๊ฐํ๋๋ผ๋ ์ฒ๋ฆฌํ์ง ์๋๋ค.
var list = [1, 2, 3];
var fn = function(el, index, all){
if(index === 0){
list.push("AB");
};
log(el)
};
list.forEach(fn);
//1
//2
//3
- ํ์ฌ ์ธ๋ฑ์ค๋ณด๋ค ํฐ ์ธ๋ฑ์ค์ ๊ฐ์ ๋ณ๊ฒฝํ๋ฉด ๋ณ๊ฒฝ๋ ๊ฐ์ ์ฌ์ฉํ๋ค.
var list = [1, 2, 3];
var fn = function(el, index, all){
if(index === 0){
list[2] = 345;
};
log(el)
};
list.forEach(fn);
//1
//2
//345
- ํ์ฌ ์ธ๋ฑ์ค๋ณด๋ค ํฐ ์ธ๋ฑ์ค์ ์๋ฆฌ๋จผํธ๋ฅผ ์ญ์ ํ๋ฉด ๋ฐฐ์ด์์ ์ญ์ ๋๋ฏ๋ก ๋ฐ๋ณต์์ ์ ์ธ๋๋ค.
var list = [1, 2, 3];
var fn = function(el, index, all){
if(index === 0){
delete list[2];
};
log(el)
};
list.forEach(fn);
//1
//2
for() vs forEach()
for() | forEach() |
|
|
'๐ฐ ์ธ์ด > JS - ๋น๊ธฐ๋ ํธ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฉ์๋ (0) | 2021.05.26 |
---|---|
ES6 - class (0) | 2021.05.25 |
ํจ์ ํ๋กํผํฐ - call, apply/ bind (0) | 2021.05.24 |
์ค๋ธ์ ํธ ํ๋กํ ํ์ (0) | 2021.05.23 |
new ์ฐ์ฐ์ (0) | 2021.05.17 |