ES6基础知识01(let,const,解构赋值)

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES6基础知识01(let,const,解构赋值)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

ES6 新增特性整理讲解

新增命令

1.let命令

ES6新增了let命令,用来声明变量。它的用法类似于var,但是也存在新的特性。

 - **let所声明的变量,只在let命令所在的代码块内有效。适用于for循环**
 
            VAR a = 3;
            var a = 4;
            
            let b = 4;
            
            {
                var a = 5;
                let b = 5;    //作用域仅在代码块内部
                let c = "this is inner c";
                var d = "this is inner d";
                console.LOG(b);    //b = 5
            }
          
            console.log(a);    //a = 5
            console.log(b);    //b = 4
            console.log(d);    //this is inner d
            console.log(c);    //c is not defined

for循环

    按理说,在执行完for循环后,应该释放变量的值,否则可能会对全局变量造成影响,因此,声明为let,会更好。
            //使用var 声明
            var result  = 0;
            for(var i = 0;i<100;i++){
                result += i;
            };
            console.log(result);    //5050
            console.log(i);    //101
            //使用let 声明
            var result  = 0;
            for(let i = 0;i<100;i++){
                result += i;
            };
            console.log(result);    //5050
            console.log(i);    // i is not defined
 - **不存在变量提升**

            //先操作
            console.log('var变量提升',a);    //undefined
            console.log('let没有变量提升',b);    //报错:b is not defined
            //再声明
            var a = 3;
            let b = 4;
           
 - **暂时性死区**

            var tmp = 123; 
            if (true) {
                tmp = 'abc'; // ReferenceError 
                let tmp; 
            } 
 - **不允许重复声明**
    ```
        var a = 3;
        var a = 4;
        
        let b = 4;
        let b = 5;     //TypeError:Duplicate declaration "b"
        console.log(a);//a = 4
        console.log(b);
    ```
    

2.const命令

基本用法:const声明一个只读常量。一旦声明,常量的值就不能改变。类似于Java中的final关键字。

      const PI = 3.1415; PI = 3; // TypeError: Assignment to constant variable

const声明的变量不得改变值,这意味着,const一旦声明变量,就必须立即初始化,不能留到以后赋值。

      const foo; // SyntaxError: Missing inITializer in const declaration

其余特点与let一样,具有不能重复声明,具有块级作用域,暂时性死区。


解构赋值

ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。例如:

let [a, b, c] = [1, 2, 3];

本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。如果解构不成功,变量的值就等于undefined。另一种情况是不完全解构,即等号左边的模式,只匹配一部分的等号右边数组。这种情况下,解构依然可以成功。

1.对象的解构赋值

a>对象的属性没有次序,变量必须与属性同名。

ES5

@H_302_406@var obj ={
    name = "tom,
    age = 12,
};
var name = obj.name;
var age = obj.age;

在ES6中

let {name:name,age:age} = obj;
let{name,age} = obj;
console.log(name,age);

b>如果变量名与属性名不一致,必须写成下面这样。

    var { foo: baz } = { foo: 'aaa', bar: 'bbb' };     //baz = "aaa”



c>嵌套解构

let obj = { p: [ 'Hello', { y: 'World' } ] }; 
let { p: [x, { y }] } = obj;     //x = "Hello”; y = "World”

d>默认值(默认值生效的条件是,对象的属性值严格等于undefined)

var {x: y = 3} = {}; y // 3



2.数组的解构赋值

let [a, b, c] = [1, 2, 3];

a>不完全解构

let [a, [b], d] = [1, [2, 3], 4];    //a = 1; b = 2; d = 4 

b>集合解构

let [head, ...tail] = [1, 2, 3, 4];     //head = 1; tail = [2, 3, 4]

c>默认值(当匹配值严格等于undefined时,默认值生效)

let [x, y = 'b'] = ['a'];     // x='a', y='b’

d>默认值也可以为函数

function f() { console.log('aaa'); } 
let [x = f()] = [1]; 



let [a,b,...c] = ["terry","lerry","tom","jack"];
console.log(a);    //terry;
console.log(b);    //lerry;
console.log(c);    //["tom","jack"]

3.字符串的解构赋值
a>解构时,字符串被转换成了一个类似数组的对象。

const [a, b, c, d, e] = ‘hello’;    //a=h;b=e;c=l;d=l;e=o

b>也可以对数组的属性解构

let {length : len} = ‘hello’;     //len = 5

c> 数值和布尔值解构赋值

解构时,如果等号右边是数值和布尔值,则会先转为对象
let {toString: s} = 123;     //s === Number.PRototype.toString true
let {toString: s} = true;     //s === Boolean.prototype.toString true

4.函数参数的解构赋值
基本语法:

function add([x, y]){ return x + y; } 
add([1, 2]);

默认值:

function move({x = 0, y = 0} = {}) {
     return [x, y]; 
} 
move({x: 3, y: 8}); // [3, 8] 
move({x: 3}); // [3, 0] 
move({});     // [0, 0]
move();     // [0, 0]
    

解构赋值的常见用途

1.交换变量的值

let x = 1; let y = 2; [x, y] = [y, x];

2.从函数返回多个值

function example() { return [1, 2, 3]; } 
let [a, b, c] = example();

3.函数参数的定义

function f([x, y, z]) { ... } 
f([1, 2, 3]);

4.提取JSON数据

let jsonData = { id: 42, status: "OK", data: [867, 5309] }; 
let { id, status, data: number } = jsonData;

5.输入模块的指定方法

const { SourceMapConsumer, SourceNode } = require("source-map");

6.函数参数的默认值

jquery.ajax = function (url, { 
    async = true, cache = true, global = true, 
    beforeSend = function () {}, 
    complete = function () {},     
    // ... more config 
}) { // ... do stuff };

7..指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句
遍历map结构

var map = new Map(); 
map.set('First', 'hello'); 
map.set('second', 'world'); 
for (let [key, value] of map) { 
    console.log(key + " is " + value); 
}

--------------------------------------------------------------------本次结束-------------------------

脚本宝典总结

以上是脚本宝典为你收集整理的ES6基础知识01(let,const,解构赋值)全部内容,希望文章能够帮你解决ES6基础知识01(let,const,解构赋值)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。