forEach

์ถœ๋ ฅ์ด๋ฒˆ์—” forEach๋ฌธ์„ ๋ฐฐ์šฐ๊ณ  ์–ด์ œ ๋งŒ๋“  ๋ฐ˜๋ณต๋ฌธ์„ ์ˆ˜์ •ํ•ด๋ณด์ž.

var pantsSize = [26,28,30,32,34];

pantsSize.forEach(function(){
    console.log("1");   //1์ด ๋‹ค์„ฏ๋ฒˆ ์ถœ๋ ฅ๋จ
})
 pantsSize.forEach(function (size, index){
      console.log(size, index);   
 })

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋ฐ˜๋ณต๋ฌธ ๋Œ๋•Œ๋งˆ๋‹ค size ๋Š”pantsSize ์•ˆ์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ๋˜๊ณ 

index๋Š” 0๋ถ€ํ„ฐ 1์”ฉ ์ฆ๊ฐ€ํ•˜๋Š” ์ •์ˆ˜๊ฐ€ ๋œ๋‹ค.

์ง€๋‚œ์‹œ๊ฐ„์— ๋งŒ๋“ค์—ˆ๋˜ ๋ฐ˜๋ณต๋ฌธ์„ ์ด๋ ‡๊ฒŒ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.

//for๋ฌธ
for(let i=0; i<pantsSize.length; i++){
    $('.form-select').eq(1).append("<option>"+pantsSize[i] +"</option>")
}

//forEach๋ฌธ 
pantsSize.forEach(function (size){
    $('.form-select').eq(1).append(`<option> ${size}</option>`);
});

โœจ ๊ณผ์ œ. var shirthSize = [95,100,105,110] ์„ ์ƒ์„ฑํ•˜๊ณ  forEach๋ฌธ์„ ์‚ฌ์šฉํ•ด ์…”์ธ  ํด๋ฆญ ์‹œ ๋‚˜ํƒ€๋‚˜๊ฒŒ ํ•ด๋ณด์ž.

for in

Object ์ž๋ฃŒ๋Š” for in ๋ฐ˜๋ณต๋ฌธ์„ ์“ด๋‹ค.

var obj = {name : "ํŽ˜๋ผ๋ฆฌ", price: 15000};
for(var key in obj){
  console.log("1"); // 1์ด 2๋ฒˆ ์ถœ๋ ฅ๋จ
  console.log(key);     // key name, pirce ๊ฐ€ ์ถœ๋ ฅ๋จ  
  console.log(obj[key]);   //ํ•ด๋‹น key์˜ value๊ฐ€ ์ถœ๋ ฅ๋จ
}

๐Ÿš€์‹ฌํ™” arrow function

ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ๋Š” ๋‹ค๋ฅธ ๋ฌธ๋ฒ•

์ฝœ๋ฐฑํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค ๋•Œ ์ž์ฃผ์“ด๋‹ค.

 pantsSize.forEach((size) => {
    console.log("arrow funtion", size);
 })

์ผ๋ฐ˜ ํ•จ์ˆ˜์™€ arrow function์˜ ์ฐจ์ด์ 

ํ•จ์ˆ˜ ์•ˆ์—์„œ this๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ

์ผ๋ฐ˜ ํ•จ์ˆ˜๋Š” this๋ฅผ ํ•จ์ˆ˜์•ˆ์—์„œ ์žฌ์ •์˜ ํ•ด์ค€๋‹ค.

arrow function์€ ์žฌ์ •์˜ ํ•ด์ฃผ์ง€์•Š๊ณ  ๋ฐ”๊นฅ์— ์žˆ๋˜ this๋ฅผ ๊ทธ๋Œ€๋กœ ์“ด๋‹ค.

์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ์ฝœ๋ฐฑํ•จ์ˆ˜ ์•ˆ์—์„œ this๋ฅผ ์จ์•ผํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” arrow function ๋ง๊ณ  ์ผ๋ฐ˜ ํ•จ์ˆ˜๋ฅผ ์“ฐ์ž.

Last updated