美文网首页
结构赋值

结构赋值

作者: 北方有嘉木24 | 来源:发表于2019-12-29 12:17 被阅读0次

    数组的结构赋值

    按顺序排列,取值由位置决定

        let [a, b, c] = [1, 2, 3]
        a //1
        b //2
        c //3
        let  [x, y, ...z] = ['a'];
        x // a
        y //undefined 结构不成功
        z //[]
        let [e, f, g] = [1, [2, 3], 4];
        e //1
        f //2 不完全结构
        g //4
        let [foo] = 1;//报错,右边等号的值或者转为对象以后必须具备Iterator接口
        let [f = true] = [];
        f //true 默认值
    

    对象的机构赋值

    变量名与属性名必须相同才能取值,先找到同名属性,在赋值给对应的变量,真正被复制的是变量

        let {bar, foo} = {
            foo: "aaa",
            bar: "bbb"
        };
        bar //bbb
        foo //aaa
        let baz = {
            foo: "aaa",
            bar: "bbb"
        };
        baz //undefined
        var {foo: baz} = {
            foo: "aaa",
            bar: "bbb"
        };
        baz // aaa
    

    嵌套赋值

        let obj = {
            p: [
                "hello",
                {y: 'world'}
            ]
        };
        let {p: [x, {y}]} = obj;
        x //hello
        y //world
        let {p, {p: [x, {y}]}} = obj;
        x //hello
        y //world
        p //["hello", {y: "world"}]
    

    默认赋值

    必须严格等于undefined,结构赋值失败值等于undefined

    其他

    子串会被解析为一个类数组

        let [a, c] = "ad";
        a //"a"
        c //"d"
    

    布尔与数字的结构赋值

    等号做组边是数字或者布尔是,会先转换为对象。null和undefined无法转换为对象,报错

        let {to: s} = 123;
        s// undefined Number 沒有to方法
        let {toString: ss} = 123;
        ss //toString() { [native code] }
        //ss === Number.prototype.toString true
        // s === Number.prototype.toString false
        let {prop: x} = undefined; // TypeError
    

    用途

    1、交互变量

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

    2、读取函数返回值

        function fn(){
            return [1, 2, 3];
        }
        let [a, b, c] = fn();
        function fn1(){
            return {
                foo: 1,
                bar: 2
            }
        }
        let {foo, bar} = fn1();
        foo //1
        bar //2
    

    相关文章

      网友评论

          本文标题:结构赋值

          本文链接:https://www.haomeiwen.com/subject/hkryoctx.html