ES6-变量的解构赋值

21 篇文章 1 订阅
7 篇文章 1 订阅

数组的解构赋值

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

    var [p, q = "aaa"] = ["bbb", undefined]
    console.log(p, q) // bbb aaa
    var [temp = "string"] = ["tempString"]
    console.log(temp) // tempString
    
  • 不完全解构
    等号左边的模式,只匹配一部分的等号右边的数组。

  • 指定默认值
    注意:ES6内部使用严格相等运算符(===)判断一个位置是否有值。所以,如果一个数组成员不严格等于undefined,默认值是不会生效的。

    var [p, q = "aaa"] = ["bbb", undefined]
    console.log(p, q)
    var [temp = "string"] = ["tempString"]
    console.log(temp)
    
  • let和const命令
    只要某种数据结构具有Iterator接口,都可以采用数组形式的解构赋值。

    let [a, b, c] = new Set(["a", "b", "c"]);
    console.log(a)  // a
    console.log(b)  // b
    console.log(c)  // c
    
    function* fibs() {
    	let a = 0;
    	let b = 1;
    	while (true){
    		yield a;
    		[a, b] = [b, a + b];
    	}
    }
    var [first, second, third, fourth, fifth, sixth] = fibs()
    console.log(sixth)  // 5
    
  • 非遍历解构–报错

    //var [temp] = 1; 			//TypeError: 1[Symbol.iterator] is not a function
    //var [temp] = false;		//TypeError: false[Symbol.iterator] is not a function
    //var [temp] = NaN;			//TypeError: NaN[Symbol.iterator] is not a function
    //var [temp] = undefined;	//TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
    var [temp] = null;			//TypeError: Cannot read property 'Symbol(Symbol.iterator)' of object
    

对象的解构赋值

  • 解构不仅可以用于数组,还可以用于对象
    对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

var { name, age, id} = { id:“007”, name:“lenhart”, age:111 }
console.log(name,age,id) // lenhart 111 007
```

  • 指定默认值
    默认值生效的条件是,对象的属性值严格等于undefined。

  • 现有对象的方法
    对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量

    console .log(Math.sin(Math.PI/6))   // 0.49999999999999994
    
    let { sin, cos, tan, PI } = Math;
    console.log(sin(Math.PI/6))         //0.49999999999999994
    console.log(sin(PI/6))              //0.49999999999999994
    

字符串的解构赋值

  • 字符串也可以解构赋值
    字符串被转换成了一个类似数组的对象。

    const [ a, b, c, d, e ] = "Hello";
    console.log(a)  //H
    console.log(b)  //e
    console.log(c)  //l
    console.log(d)  //l
    console.log(e)  //o
    
  • 属性解构赋值
    类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

    const { length: len } = "Hello";
    console.log(len)    //5
    
    const { length } = "Hello World"
    console.log(length) //12
    

##函数参数的解构赋值

  • 函数的参数也可以使用解构。

    function sum([x, y]) {
        return x + y;
    }
    console.log(sum([1, 2]))
    
  • 函数参数的解构也可以使用默认值。

     function sum([x, y]) {
        return x + y;
    }
    console.log(sum([1, 2])) // 3
    
  • 函数参数解构赋值的默认值为undefined的时候

    function fun({x, y} = {x: 0, y:0}) {
        return [x, y]
    }
    console.log(fun({x: 100, y: 200}))  //[100, 200] 在传参的时候进行解构赋值
    console.log(fun({x: 100}))          //[100, undefined] 没有传入的参数就是undefined
    console.log(fun({}))          //[undefined, undefined] 没有传入的参数就是undefined
    console.log(fun())          //[0, 0] 没有在函数参数中进行解构赋值,而是在函数内部进行了解构赋值
    

解构赋值的用途

  • 交换变量的值

    // ES6
    console.log("ES6:");
    var x = 100;
    var y = 200;
    console.log("交换前:");
    console.log("a = " + x);
    console.log("b = " + y);
    [ x, y ] = [ y, x ];
    console.log("交换后:");
    console.log("a = " + x);
    console.log("b = " + y);
    
  • 从函数返回多个值

    function fun() {
        return [1, 2, 3];
    }
    
    var [x, y, z] = fun();
    console.log(x); //1
    console.log(y); //2
    console.log(z); //3
    
  • 函数参数的定义

    function fun([x, y, z]) {
        //  x = 100
        //  y = 200
        //  z = 300
    }
    fun([100, 200, 300]);
    
    //  参数是一组无次序的值
    function fun({id, name, age}) {
        //  id   = "110119911"
        //  name = "Lenhart"
        //  age = 24
    
    }
    fun({id: "110119911", name: "Lenhart", age: 24})
    
  • 提取Json数据

    var jsonData = {
            id: "110119911",
            name: "Lenhart",
            age: 24,
            score: {
                Chinese: 107,
                Math: 97,
                Engilsh: 119
            }
        };
        console.log(jsonData)
    
    console.log("ES5:")
    console.log("Person's number is:" + jsonData.id)
    console.log("Person's name is:" + jsonData.name)
    console.log("Person's age is:" + jsonData.age)
    console.log("Person's Chinese is:" + jsonData.score.Chinese)
    console.log("Person's Math is:" + jsonData.score.Math)
    console.log("Person's Engilsh is:" + jsonData.score.Engilsh)
    
    console.log("ES6:")
    let { id: number, name, age, score: score} = jsonData;
    console.log("Person's number is:" + number)
    console.log("Person's name is:" + name)
    console.log("Person's age is:" + age)
    console.log("Person's score is:" + score)
    console.log("Person's Engilsh is:" + score.Engilsh)
    console.log("Person's Chinese is:" + score.Chinese)
    console.log("Person's Math is:" + score.Math)
    
  • 函数参数的默认值

     jQuery.ajax = function (url,{
        async = true,
        beforeSend = function () {},
        cache = true,
        complete = function () {},
        crossDomain = false,
        global = true,
        // ...more config
    }) {
        // ...do stuff
    }
    // 避免了在函数体内部再写 var foo = config.foo || 'default foo' 这样的语句
    
  • 遍历Map结构

    var map = new Map();
    map.set("id", "110119911");
    map.set("name", "Lenhart");
    
    console.log(map);
    console.log(typeof(map));
    
    // 获取键名和键值
    for (let [key, value] of map) {
        console.log(key + " is " + value);
    }
    // id is 110119911
    // name is Lenhart
    
    // 获取键名
    for (let [key] of map) {
        console.log(key);
    }
    // id
    // name
    
    // 获取键值
    for (let [ , value] of map) {
        console.log(value);
    }
    // 110119911
    // Lenhart
    
  • 输入模块的指定方法
    输入的模块一般是不会变动的,最好使用 const 来定义

    const {SourceMapConsumer, SourceNode} = require("source-map");
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值