20190610 ES6-解構賦值-數值、布爾值、函數參數、用途

數值和布爾值的解構賦值

解構賦值的規則:ajax

  • 只要等於號右邊的值不是對象,則優先將其轉爲對象
let {toString: s} = 123;
s === Number.proptotype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString  // true

函數參數的解構賦值

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

add([1,2]) // 3

函數add的參數實際上不是一個數組,而是經過解構獲得的變量x和y。json

函數參數的解構依舊可使用默認值數組

function move({x = 0, y = 0} = {}){
    retrun [x,y]
}
move({x: 3,y: 8}); // [3,8];
move({x: 3}) // [3,0]
move({}) // [0,0]
move() // [0,0]

函數move的參數是一個對象,經過對這個對象進行解構,獲得變量x和y的值。若是解構失敗,則返回默認值。async

下面的寫法,會存在一些問題
function move({x,y} = {x: 0,y: 0}){
    return [x,y];
}
move({x: 3,y: 8}); // [3,8];
move({x: 3}) // [3,undefined]
move({}) // [undefined,undefined]
move() // [0,0]

若是已經存在賦值,則會獲取獲取undefind函數

解構賦值的用途

變換變量的值

[x,y]=[y,x]

從函數中返回多個值

// 返回一個數組
function f(){
    return [1,2,3];
}

var [a,b,c] = f(); 

// 返回一個對象
function f1(){
    ruturn {
        foo: 1,
        bar: 2
    }
}
var {foo, bar} = f1();

函數參數的定義

function f([x,y,z]){...}
f({1,2,3})

function f([x,y,z]){...}
f({x:1,z:3,y:2})

提取JSON數據

var jsonData= {
    id: 42,
    status: 'ok',
}

let {id,status: isok} = jsonData;
consoloe.log(id, isok); // 42 "OK"

函數參數的默認值

$.ajax=function (url,(
    async = true,
    beforeSend = function(){},
    cache = true,
    complete = function(){},
    crossDomain = false,
    global = true,
)){
    // TODO
}

遍歷Map解構

var map = new Map() ;

map.set('first', 'hello');
map.set('sec', 'world');

for(let [key, value] of map){
    // 從循環的數值中依次賦值key和value
    console.log(key + "is" + value)
    // first is hello 
    // sec is world 
}

輸入模塊的制定方法

const { SourceMapConsumer, SourceNode} = require("source-map")

圓括號的問題

  • 變量聲明語句中,模式中不能有圓括號
var [(a)]=[1];
var [x: {c}]={};
  • 函數參數中,模式不能帶有圓括號
function f([(z)]) = { return z; }
  • 不能講整個模式或嵌套模式中的一層放在圓括號中
({p: a})={p: 42}
([a]) = [5]

何正確的使用圓括號

  • 賦值語句的非模式部分可使用圓括號
[(b)] = [3];
({p: (d)} = {})
相關文章
相關標籤/搜索