zoukankan      html  css  js  c++  java
  • ES6入门教程---变量和常量

    ES6提出了两个新的声明变量的命令:let 和 const 
    1. 建议不再使用var,而使用let 和const 。优先使用const。

    在定义之后值是固定不变的,即为常量
    常量的值不能修改,但是如果常量保存的是一个对象,那么对象的属性是可以被修改的。

    const a = 1;

    a = 2;
    console.log(a);//报错

     const a = {
       name:'leo'
     };
     a.name = 'momo';
     console.log(a.name);   //momo

    let特性:
      1、不允许重复声明
      2、没有预解析。
      3、块级作用域

    一对{}包括的区域称为代码块
    块级作用域指一个变量或者函数只在该区域才起作用。
    从块的开始到声明这段的区域 暂存死区。

    举个常见的例子

    用var依次循环输出i,就要用到闭包

    for(var i=0;i<10;i++){
      (function(i){
             setTimeout(function(){
           console.log(i);
         })
           })(i)
     }

    用let依次循环输出i,就很方便

    for(let i=0;i<10;i++){
      setTimeout(function(){
         console.log(i);
       })
    }

    应用实例

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Document</title>
      <style type="text/css">
      div{
        display: none;
      }
      .show{
        display: block;
      }
      .active{
        background-color: yellow;
      }
      </style>
    </head>
    <body>
      <input type="button" value="tab1" class="active">
      <input type="button" value="tab2">
      <input type="button" value="tab3">
      <div class="show">div1</div>
      <div>div2</div>
      <div>div3</div>
      <script type="text/javascript">
      "use strict"

      var tabs = document.getElementsByTagName('input');

      var divs = document.getElementsByTagName('div');

      for(let i=0;i<tabs.length;i++){
        tabs[i].onclick = function(){
          for(var j=0;j<tabs.length;j++){
            divs[j].className = '';
            tabs[j].className = '';
           }
          this.className = 'active';
          divs[i].className = 'show';
        }
      }
      </script>
    </body>
    </html>

  • 相关阅读:
    android 中文 api (43) —— Chronometer
    SVN客户端清除密码
    Android 中文 API (35) —— ImageSwitcher
    Android 中文API (46) —— SimpleAdapter
    Android 中文 API (28) —— CheckedTextView
    Android 中文 API (36) —— Toast
    Android 中文 API (29) —— CompoundButton
    android 中文 API (41) —— RatingBar.OnRatingBarChangeListener
    Android 中文 API (30) —— CompoundButton.OnCheckedChangeListener
    Android 中文 API (24) —— MultiAutoCompleteTextView.CommaTokenizer
  • 原文地址:https://www.cnblogs.com/xuniannian/p/8288909.html
Copyright © 2011-2022 走看看