zoukankan      html  css  js  c++  java
  • ES6中变量let的属性以及在for循环中的使用

    let和var的差别

    1、let没有变量提升,申明变量的同时必须对变量赋值

    2、let不允许重复申明变量

    3、let的作用域是块级作用域,这一点在for循环中可以提现

    <ul id="ul1">
      <li class="li">1</li>
      <li class="li">2</li>
      <li class="li">3</li>
      <li class="li">4</li>
    </ul>

    <script>

    window.onload = function () {
      var app = document.getElementsByClassName('li');

      // for循环变量输出
      // for (var i = 0; i < app.length; i++) {
        // // 在for循环里绑定的事件要等循环结束后才会执行
        // app[i].onclick = function () {
        // console.log(i)
        // };
      // }
      // // 第一个循环这里点击输出的都是4


      // // 第一个for循环拆解后就是下面这个for循环
        // for (var i = 0; i < app.length; i++) {
          // var ss = function () {
            // console.log(i)
          // };
        // }
      // // 在for循环运行结束后再执行点击事件,调用ss函数,此时变量i的值当然是4
      // app[0].onclick = ss
      // app[1].onclick = ss
      // app[2].onclick = ss
      // app[3].onclick = ss

      // let申明的变量只在块级作用域{}中,所以在for循环外调用会报undefined
      // for (let i = 0; i < app.length; i++) {
        // let ss = function () {
          // console.log(i)
        // };
      // }
      // // 在for循环运行结束调用ss报错
      // app[0].onclick = ss
      // app[1].onclick = ss
      // app[2].onclick = ss
      // app[3].onclick = ss


      // 使用let变量可以直接在for循环变量输出i
      for (let i = 0; i < app.length; i++) {
        app[i].onclick = function () {
          console.log(i)
        };
      }
    }

      

    </script>

  • 相关阅读:
    安装maven报错及解决
    Servlet包导入
    理解SQL SERVER的逻辑读,预读和物理读以及索引
    第六章(函数)编程题二
    第六章(函数)编程题一
    第五章(使用对象) 编程题一
    第三章(循环) 编程题 4
    第四章(数组) 编程题 1
    第三章(循环) 编程题 3
    低功耗蓝牙 ATT/GATT/Service/Characteristic 规格解读
  • 原文地址:https://www.cnblogs.com/webwangjie/p/9370763.html
Copyright © 2011-2022 走看看