一、let关键字(一)
-
let关键字就是用来声明变量的
-
使用let关键字声明的变量具有块级作用域
-
在一个大括号中 使用let关键字声明的变量才具有块级作用域,var是不具备这个特点的
-
优势:防止循环变量变成全局变量
1.let关键字是用来声明变量的
let a = 10, console.log(a);
2.使用let关键字声明的变量具有块级作用域
if(true){
let a = 10;
console.log(a);
if(true){
let b = 20;
}
console.log(b);
}
console.log(a);
上例代码可以得知:
第一个console.log(a);运行结果为10;
下面的console.log(b);和console.log(a);分别为 b is not defined和a is not defined,证实了let关键字是具有块级作用域的,循环体外不执行的。
3.在一个大括号中,使用let关键字声明的变量才具有块级作用域,var关键字是不具备这个特点的
if(true){
let num = 100;
var abc = 200;
}
console.log(num);
console.log(abc);
上述代码执行结果为num is not defined和 200
因为var不具备块级作用域,所以可以在循环体外边执行
4.防止循环变量成为全局变量
for( var = 0; i < 2; i++){
}console.log(i);
运行结果为2;
for( let = 0; i < 2; i++){
}console.log(i);
运行结果为 i is not defined;
let关键字在for循环中定义,在循环外输出的时候,结果为未定义,也证实了let关键字的一大优势,防止循环变量成为全局变量。
二、let关键字(二)
1.使用let关键字声明的变量没有变量提升
console.log(a);
let a = 10;
输出结果为 a is not defined;
2.使用let关键字声明的变量具有暂时性死区特性
var num = 10;
if(true){[
console.log(num);
let num = 20;
]}
在循环体内使用了他关键字声明变量,会和整个块级作用域进行绑定,与外部声明的变量没有关系,所以输出的结果还是 num is not defined;
let关键字经典面试题(一)
var arr = [];
for (var i = 0; i < 2; i++){
arr[i] = function () {
console.log(i);
}
}
arr[0]();
arr[1]();
输出结果为2;
调用的函数体中没有定义变量,根据作用域链的方法,应该往上找变量,所以就是外部的全局变量。由于在根据下标函数调用时,函数内部的执行已经结束了,所以不满足全局的条件的那个数就是最后输出的值。
关键点:变量i是全局的,函数执行时输出的都是全局作用域下的i值
let关键字经典面试题(二)
let arr = [];
for (var i = 0; i < 2; i++){
arr[i] = function () {
console.log(i);
}
}
arr[0]();
arr[1]();
输出结果为0和1;
关键点:每次循环都会产生一个块级作用域,每个块级作用域的变量都是不同的,函数执行时输出的是自己的上一级(循环产生的块级作用域)作用域下的值。
三、const关键字
作用:声明常量,常量的值就是值(内存地址)不能变化的量。
1.具有块级作用域。
if(true){
const a =10;
consol.log(a);
}
console.log(a);
输出结果为10和 a is not defined;
具有块级作用域,只有在声明的区域有用,别的地方是没有用的
if(true){
const a =10;
if(true){
const a =20;
console.log(a);
}
consol.log(a);
}
console.log(a);
输出结果为20,10,a is not defined;
2.声明常量时必须赋值,否则会报错
const a;
3.声明常量,赋值后,值不能被修改
const a = 10;
a = 20;
输出报错。
const array = [100,200];
array[0] = 123;
console.log(array);
数据结构内部的值可以被更改,但是数据本身不能被更改,可以通过下标的方式进行更改。
四、let、const、var的区别
1.使用var 声明的 变量,其作用域为该语句所在的函数内,且存在变量提升现象
2.使用let 声明的变量,其作用域为该语句所在的代码块内,不存在变量提升
3.使用const 声明的是常量,在后面出现的代码中不能再修改该常量的值
var | let | const |
---|---|---|
函数级作用域 | 块级作用域 | 块级作用域 |
变量提升 | 不存在变量提升 | 不存在变量提升 |
值可更改 | 值可更改 | 值不可更改 |
五、解构赋值
ES6中允许从数组中提取值,按照对应位置,对变量赋值。对象也可以实现解构
1.数组解构
数组解构允许我们按照一一对应的关系从数组中提取值,然后将值赋值给变量
let [a,b,c] = [1,2,3];
console.log(a);
console.log(b);
console.log(c);
如果解构不成功,变量的值为undefined。
let [foo] = [];
let [bar,foo] = [1];
2.对象解构
对象解构允许我们使用变量的名字匹配对象的属性 匹配成功将