1:交換兩個變數的值
let a = 12;
let b = 32;
[a,b] = [b,a];
console.log(a,b)
在ES6之前我們交換兩個變數的值的時候往往需要宣告一個中間變數,在ES6中可以通過解構賦值來實作,這種寫法:簡潔、易讀、語意清晰
2:函式回傳多個值
回傳一個陣列:
function exampleArr() {
return [1,2,3];
}
var [a,b,c] = exampleArr();
console.log([a,b,c]);
回傳一個物件:
function exampleObj() {
return {
foo : 1,
bar : 2,
baz : 3
}
}
var {foo ,bar ,baz} = exampleObj();
console.log(foo,bar,baz);
本質上,函式只能回傳一個值,但是可以把其放在陣列或者物件中,來回傳多個值
3:函式引數的定義:
有序的引數:
function f([x,y,z]){
console.log([x,y,z])
}
f([1,2,3]);
無序的引數:
function f({x,y,z}){
console.log({x,z,y})
}
f({z:3,x:22,y:31});
原理在于解構賦值可以將一組引數與變數名對應起來
4:提取JSON資料
var jsonData = {
id:404,
name:"tianqin",
data : [13134,15331],
status :'OK'
}
let {id, status, data:number, name} = jsonData
console.log(id,status,number,name);
5:指定函式引數的默認值
function foo({x, y = 5}) {
console.log(x, y);
}
foo({}) // undefined 5
foo({x: 1}) // 1 5
foo({x: 1, y: 2}) // 1 2
foo() // TypeError: Cannot read property 'x' of undefined
6:遍歷Map解構
var map = new Map();
map.set('first' ,'hello');
map.set('second' ,'world');
for(let [key,value] of map){
console.log(key + "is" + value);
}
獲取鍵名和鍵值非常方便
7:輸入模塊的指定方法
const {first,second} = require('xxx');
加載模塊時,需要指定輸入那些方法,解構賦值可以使得輸入陳述句非常清晰
參考文獻:
[1] 阮一峰 .《ES6標準入門(第2版)》[M].北京.電子工業出版社.2015:26-28
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/205321.html
標籤:其他
上一篇:CF57C Array
