• Js变量的解构赋值


    解构:从数组和对象中提取值,对变量进行赋值。

    一、数组的解构赋值

    1.数组的元素是按次序排列的,变量的取值由它的位置决定

    // 模式匹配
    
    let [a, b, c] = [1, 2, 3];
    
    let [foo, [[bar], baz]] = [1, [[2], 3]];
    foo // 1
    bar // 2
    baz // 3
    
    let [ , , third] = ["foo", "bar", "baz"];
    third // "baz"
    
    let [x, , y] = [1, 2, 3];
    x // 1
    y // 3
    
    let [head, ...tail] = [1, 2, 3, 4];
    head // 1
    tail // [2, 3, 4]
    
    let [x, y, ...z] = ['a'];
    x // "a"
    y // undefined
    z // []

    2.默认值

    // 当一个数组成员严格等于undefined,默认值才会生效
    
    let [foo = true] = [];
    foo // true
    
    let [x, y = 'b'] = ['a']; // x='a', y='b'
    let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
    
    
    // 默认值可以引用解构赋值的其他变量,但该变量必须已经声明。
    
    let [x = 1, y = x] = [];     // x=1; y=1
    let [x = 1, y = x] = [2];    // x=2; y=2
    let [x = 1, y = x] = [1, 2]; // x=1; y=2
    let [x = y, y = 1] = [];     // ReferenceError: y is not defined

    资源搜索网站大全 https://www.renrenfan.com.cn 广州VI设计公司https://www.houdianzi.com

    二、对象的解构赋值

    1.对象的属性没有次序,变量必须与属性同名,才能取到正确的值。对象的解构赋值可以取到继承的属性。

    let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
    foo // "aaa"
    bar // "bbb"
    
    let { baz } = { foo: 'aaa', bar: 'bbb' };
    baz // undefined
    
    
    // 例一
    let { log, sin, cos } = Math;
    
    // 例二
    const { log } = console;
    log('hello') // hello
    
    //如果变量名与属性名不一致,必须写成下面这样。
    let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
    baz // "aaa"
    
    let obj = { first: 'hello', last: 'world' };
    let { first: f, last: l } = obj;
    f // 'hello'
    l // 'world'
    
    

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

    var {x = 3} = {};
    x // 3
    
    var {x, y = 5} = {x: 1};
    x // 1
    y // 5
    
    var {x: y = 3} = {};
    y // 3
    
    var {x: y = 3} = {x: 5};
    y // 5
    
    var { message: msg = 'Something went wrong' } = {};
    msg // "Something went wrong"
  • 相关阅读:
    nightwatchjs --Expect element to not include text
    Iterating elements using NightWatchJS
    nightwatch 切换窗口
    nodejs读取配置文件
    spring 事务
    重载,重写,重构
    python 元组不变 列表可变
    WebStorm ES6 语法支持设置
    docker日志
    curl -O 下载文件
  • 原文地址:https://www.cnblogs.com/xiaonian8/p/14124298.html
Copyright © 2020-2023  润新知