ES6 之 let 和 const关键字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z_x_Qiang/article/details/86619784

1. let 关键字

1.与var类似, 用于声明一个变量;
2. 特点:
  * 在块作用域内有效
  * 不能重复声明
  * 不会预处理, 不存在提升
3. 应用:
  * 循环遍历加监听
  * 使用let取代var是趋势
<script type="text/javascript">
    //console.log(age);// age is not defined
    let age = 12;
    //let age = 13;不能重复声明
    console.log(age);
    let btns = document.getElementsByTagName('button');
    for(let i = 0;i<btns.length;i++){
            btns[i].onclick = function () {
                alert(i);
            }
    }

</script>

2.const关键字

1. 作用:
  * 定义一个常量
2. 特点:
  * 不能修改
  * 其它特点同let
3. 应用:
  * 保存不用改变的数据
<script type="text/javascript">
    const sex = '男';
    console.log(sex);
    //sex = '女';//不能修改
    console.log(sex);
</script>

猜你喜欢

转载自blog.csdn.net/z_x_Qiang/article/details/86619784