πŸ‘‹ let λ³€μˆ˜μ™€ var λ³€μˆ˜ 차이


πŸ’‘ μš”μ•½

  • for()λ¬Έμ—μ„œ 반볡 ν•  λ•Œλ§ˆλ‹€

    • var λ³€μˆ˜λŠ” μŠ€μ½”ν”„λ₯Ό 갖지 μ•ŠμŒ
    • let λ³€μˆ˜λŠ” μŠ€μ½”ν”„λ₯Ό 가짐

1) var λ³€μˆ˜μ™€ μŠ€μ½”ν”„

// varλ³€μˆ˜μ™€ μŠ€μ½”ν”„

var node = document.querySelector('.sports');

for (var k = 0; k < node.children.length; k++) {
  node.children[k].onclick = function (event) {
    event.target.style.backgroundColor = 'yellow';
    console.log(k);
  };
}
  1. μ–΄λ–€ 것을 ν΄λ¦­ν•˜λ”λΌλ„ 항상 for()문이 끝났을 λ•Œμ˜ 값인 3을 좜λ ₯함

    • μ „μ²΄μ˜ μŠ€μ½”ν”„μ—μ„œ ν•˜λ‚˜μ˜ κ°’μœΌλ‘œ ν• λ‹Ήλ˜κΈ° λ•Œλ¬Έ
    • for문의 λ§ˆμ§€λ§‰ 값인 3이 var μ„ μ–Έλœ k 즉 κΈ€λ‘œλ²Œ λ³€μˆ˜μ— ν• λ‹Ή 됨.
  2. var k = 0; μ—μ„œ k λ³€μˆ˜μ˜ μŠ€μ½”ν”„λŠ” ν•¨μˆ˜ μž„

2) let λ³€μˆ˜μ™€ μŠ€μ½”ν”„

// letλ³€μˆ˜μ™€ μŠ€μ½”ν”„

var node = document.querySelector('.sports');

for (let k = 0; k < node.children.length; k++) {
  node.children[k].onclick = function (event) {
    event.target.style.backgroundColor = 'yellow';
    console.log(k);
  };
}

// 0
// 1
// 2
  • 이벀트λ₯Ό μ„€μ •ν•  λ•Œμ˜ k값을 좜λ ₯ ν•©λ‹ˆλ‹€.