for + let
HTML
<h1>for + let</h1>
<h2>参考リンク</h2>
<ul>
<li><a href="https://teratail.com/questions/205789#">JavaScript - for文における、letとvarの挙動の違い|teratail</a></li>
<li><a href="http://kangax.github.io/compat-table/es6/#test-let_for/for-in_loop_iteration_scope">for/for-in loop iteration scope - ECMAScript 6 compatibility table</a></li>
</ul>
<h2>let + var (type1) ※IE11は未対応</h2>
<p class="plus1">+</p>
<p class="plus1">+</p>
<p class="plus1">+</p>
<h2>let + var (type2) ※ブロックスコープの再現コード</h2>
<p class="plus2">+</p>
<p class="plus2">+</p>
<p class="plus2">+</p>
<script>
'use strict';
/*
* type 1
*/
const plus1 = document.querySelectorAll('.plus1');
for (let i = 0; i < plus1.length; i++) {
plus1[i].addEventListener('click', function handleClick () {
console.log(i);
plus1[i].textContent = plus1[i].textContent === '+' ? '-' : '+';
}, false);
}
</script>
<script>
'use strict';
/*
* type 2
*/
const plus2 = document.querySelectorAll('.plus2');
for (let i = 0; i < plus2.length; i++) {
let i2 = i;
plus2[i2].addEventListener('click', function handleClick () {
console.log(i2);
plus2[i2].textContent = plus2[i2].textContent === '+' ? '-' : '+';
}, false);
}
</script>
CSS
.plus1,.plus2 {
color: #00AED9;
text-align: center;
line-height: 15px;
border: solid #DADADA 2px;
border-radius: 50%;
width: 20px;
height: 20px;
font-weight: bold;
font-size: 20px;
}