๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ฐ ์–ธ์–ด/JS - ๋น„๊ธฐ๋„ˆ ํŽธ

for()๊ณผ forEach()

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()
  • ํ•จ์ˆ˜ ์ฝ”๋“œ๋ฅผ ์ฝ์–ด์•ผ ์•Œ ์–ด๋–ค ๋ฐ˜๋ณต์„ ํ•  ์ง€ ์•Œ ์ˆ˜ ์žˆ๋‹ค.
  • ์ธ๋ฑ์Šค ์ฆ๊ฐ€ ๊ฐ’์„ ์กฐ์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • break, continue๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.
  • ์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค๋Š” ์‹œ๋งจํ‹ฑ, ๋ฐ˜๋ณต ์ค‘๊ฐ„์— ๋๋‚˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์‹œ๋งจํ‹ฑ
  • ์‹œ๋งจํ‹ฑ์œผ๋กœ ์†Œ์Šค ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ ํ–ฅ์ƒ
  • ์ธ๋ฑ์Šค ์ฆ๊ฐ€ ๊ฐ’์„ ์กฐ์ •ํ•  ์ˆ˜ ์—†๋‹ค.
  • break, continue์˜ ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€ํ•˜์ง€๋งŒ, throw๋Š” ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.