变量的解构赋值

1、数组解构赋值

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

按顺序赋值

解构不成功,默认值为undifined

只要某种数据结构具有Iterator接口,都可以采用数组解构,如Set解构

可设置默认值

2、对象解构赋值

let {a, b} = {a: 111, b:222}

按同名属性解构

解构不成功,默认值为undifined

可设置默认值

3、字符串解构赋值

let [a, b, c, d, e] = 'hello'

4、函数参数解构赋值

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

[[1,2], [3, 4]].map(([a, b]) => a + b)

function move({x = 0, y = 0} = {}){
  return [x, y]
}

5、解构常见用途

交换变量的值

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

从函数中返回多个值,数组和对象都可以

function test(){
    return [1, 2, 3]    
}

let [a, b, c] = test()

函数参数的解构定义,通过一个数组参数或者对象参数解构;该方法也可以通过方法的默认参数达到相同效果,都可以做到方法的安全扩展

// 早期方法定义,及调用
function foo([a]){
    // handler    
}

foo(1)  // 早期代码

// 后期定义,参数解构赋值
function foo([a, b = 0]){
    // handler    
}

foo(1)
foo(1, 2)

提取json数据

let json = {
    id: 20,
    status: 200,
    data: [100, 200]  
}
let {id, status, data} = json

函数参数默认值

JQuery.ajax = function (url, {
    async = true,
    beforeSend = function(){},
    cache = true,
    complete =  function(){},
    ...
}){

}

遍历map解构

for(let [key, value] of map){      
}

for(let [key] of map){      
}

for(let [, value] of map){      
}

输入模块的指定方法

const {modal1, modal 2} = require("modal")

 

posted @ 2022-06-21 17:58  贰零伍零  阅读(37)  评论(0)    收藏  举报