[TIL] forEach()

welcomeยท2021๋…„ 10์›” 13์ผ
0

๊ตฌ๋ฌธ

arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])

์ฐธ๊ณ ) [] ๋Š” optional

forEach()๋Š” ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉด์„œ ๋ฐฐ์—ด์˜ ๊ฐ ์›์†Œ๋“ค์„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

const nations = ["korea", "usa", "china", "japan"];

nations.forEach((nation) => {
  console.log(nation);

});

// korea
// usa
// china
// japan

return ์„ ์‚ฌ์šฉํ•˜๋ฉด ์ค‘๊ฐ„์— ๋ฐ˜๋ณต๋ฌธ์„ ํƒˆ์ถœํ• ์ˆ˜ ์žˆ์œผ๋ฉฐ ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ idx๋ฅผ ์‚ฌ์šฉํ•ด index๋ฅผ ์•Œ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

let idxOfC = -1;
let arr = ['a', 'b', 'c', 'd'];

arr.forEach((el, idx) => {
  if (el === 'c') {
    idxOfC = idx;
    return;
  }
});

โœ… for๋ฌธ์€ ์ฃผ๋กœ ๋‹จ์ˆœ๋ฐ˜๋ณต์‹œ ์‚ฌ์šฉ , forEach()๋Š” array์—์„œ๋งŒ ์‚ฌ์šฉํ• ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

profile
๐Ÿ’ป

0๊ฐœ์˜ ๋Œ“๊ธ€