JavaScript 变量声明var和let的区别

var声明的变量在整个区域都是一个

let声明的变量只在局部区域有效。

 1 <html>
 2   <head>
 3    <script>
 4            function myfunction1(){
 5                var a=1;
 6                if(1){
 7                    var a=2;
 8                    console.log(a); //输出2
 9                }
10                console.log(a);    //输出2
11            }
12            function myfunction2(){
13                let a=1;
14                if(1){
15                    let a=2;
16                    console.log(a);    //输出2
17                }
18                console.log(a);    //输出1
19            }
20    </script>
21   </head>
22   <body>
23       <h1 id="h1">
24           var和let的区别
25       </h1>
26     <p id="p1">
27         let允许你声明一个作用域被限制在块级中的变量、语句或者表达式。在Function中局部变量推荐使用let变量,避免变量名冲突。
28     </p>
29     <button type="button1" onclick="myfunction1()">函数1执行</button>
30     <button type="button2" onclick="myfunction2()">函数2执行</button>
31     
32   </body>
33 </html>

从输出结果可以看出var声明的变量a可以在if中改变他的值,

而let声明的变量a=1,在if中声明的变量a=2是俩个独立的变量。

 

posted @ 2018-03-20 09:46  暖熊熊  阅读(151)  评论(0编辑  收藏  举报