es 解构

作者: pengkiw | 来源:发表于2020-06-20 17:28 被阅读0次

    1⃣️ 数组解构

    let arr = [1, 2, 3]
    let [a, b, c] = arr;
    console.log(a, b, c) // 1 2 3
    
    let arr = [1, 2, [3, 4]]
    let [a, b, c] = arr;
    console.log(a, b, c) // 1 2 [3,4]
    
    let arr = [1, 2, [3, 4]]
    let [a, b, [c, d]] = arr;
    console.log(a, b, c, d) // 1 2 3,4
    
    let [a, b, c, d] = [1, 2, [3, 4]];
    console.log(a, b, c, d) // 1 2 [3, 4] undefined
    
    let [a, b, c, d = 5] = [1, 2, [3, 4]];
    console.log(a, b, c, d) // 1 2 [3, 4] 5
    
    let [a, b, c, d = 5] = [1, 2, [3, 4], 6];
    console.log(a, b, c, d) // 1 2 [3, 4] 6
    

    2⃣️对象解构

    let user = {
        name: 'kiw',
        age: '18'
    }
    let {
        name,
        age
    } = user
    console.log(name, age)  // kiw 18
    

    别名

    let user = {
        name: 'kiw',
        age: '18'
    }
    let {
        name: uname,
        age: uage
    } = user
    console.log(uname, uage)  // kiw 18
    

    3⃣️字符串解构

    let str = 'imooc'
    let [a, b, c, d, e] = str;
    console.log(a, b, c, d, e); // i m o o c
    

    作用
    1利用解构实现 默认值 和快速赋值/传值
    2 快速提取对象/数组中的一些属性 减少代码量

    相关文章

      网友评论

          本文标题:es 解构

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