• es6 新关键字let


    let提供了另一种变量生命的方式。let关键字可以将变量绑定到所在的任意作用于中(通常 {}内部)。换句话说,ley为其声明的变量作用在了块作用域。

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <title></title>
     5     <script type="text/javascript">
     6         window.onload=function(){
     7             var list=document.getElementById("list");
     8             for(let i=0;i<5;i++){
     9                 var item=document.createElement("li");
    10                 item.appendChild(document.createTextNode("item"+i));
    11                 
    12                 item.onclick=function(ev){
    13                     console.log("item"+i+"is clicked");
    14                 };
    15                 list.appendChild(item);
    16             }
    17         }
    18     </script>
    19 </head>
    20 <body>
    21     <ul id="list">
    22         
    23     </ul>
    24 </body>
    25 </html>

    上面的代码如果换成了var i=0 那么点击只会出现item5 is clicked。然而用let 可以正常打印。因为如果换成var的话是函数级的变量,而let让他有了块作用域,指向了5个不同了内部函数。

    let  对比 var

    let的作用域是块,而var的作用域是函数

    var a = 5;
    var b = 10;
    
    if (a === 5) {
      let a = 4; // The scope is inside the if-block
      var b = 1; // The scope is inside the function
    
      console.log(a);  // 4
      console.log(b);  // 1
    } 
    
    console.log(a); // 5
    console.log(b); // 1

    let 在循环中

    可以用 let 来代替 var ,在 for 定义块中使用块级变量.

    for (let i = 0; i < 10; i++) {
      console.log(i); // 0, 1, 2, 3, 4 ... 9
    }
    
    console.log(i); // i is not defined

     

  • 相关阅读:
    linux基础命令1
    linux下nginx搭建
    linux 对外开放端口
    linux下mysql 登录修改密码与数据库备份
    linux下mysql部署
    linux下mysql启动 Starting MySQL. ERROR! The server quit without updating PID file(xxx/x.pid)
    aptitude软件状态标志i、v、p
    GNU各软件版本历史站点
    glibc库和glib库
    禁用ipv6的两种方法
  • 原文地址:https://www.cnblogs.com/ybleeho/p/7596161.html
Copyright © 2020-2023  润新知