ES6之主要知识点(二) 变量的解构赋值。默认值
生活随笔
收集整理的這篇文章主要介紹了
ES6之主要知识点(二) 变量的解构赋值。默认值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
引自http://es6.ruanyifeng.com/#docs/destructuring
- 數組解構賦值
- 默認值
- 對象解構賦值
- 用途
1.數組的解構賦值
let [a, b, c] = [1, 2, 3]; let [foo, [[bar], baz]] = [1, [[2], 3]]; foo // 1 bar // 2 baz // 3 let [ , , third] = ["foo", "bar", "baz"]; third // "baz" let [x, , y] = [1, 2, 3]; x // 1 y // 3 let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4] let [x, y, ...z] = ['a']; x // "a" y // undefined z // []因為等號右邊的值,要么轉為對象以后不具備 Iterator 接口(前五個表達式),要么本身就不具備 Iterator 接口(最后一個表達式)。
2.默認值?
let [foo = true] = []; foo // true let [x, y = 'b'] = ['a']; // x='a', y='b' let [x, y = 'b'] = ['a', undefined]; // x='a', y='b' let [x = 1] = [null]; x // null let [x = 1, y = x] = [2]; // x=2; y=23.對象的解釋構?
let { bar, foo } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb"var { foo: baz } = { foo: 'aaa', bar: 'bbb' }; baz // "aaa" let obj = {}; let arr = []; ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true }); obj // {prop:123} arr // [true]4.用途
(1)變換變量的值
let x = 1; let y = 2;[x, y] = [y, x];(2)從函數返回多個值
// 返回一個數組 function example() {return [1, 2, 3]; } let [a, b, c] = example();// 返回一個對象 function example() {return {foo: 1,bar: 2}; } let { foo, bar } = example();(3)函數參數的定義
// 參數是一組有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]);// 參數是一組無次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});(4)提取JSON數據
let jsonData = {id: 42,status: "OK",data: [867, 5309] };let { id, status, data: number } = jsonData;console.log(id, status, number); // 42, "OK", [867, 5309](5)函數參數的默認值
jQuery.ajax = function (url, {async = true,beforeSend = function () {},cache = true,complete = function () {},crossDomain = false,global = true,// ... more config }) {// ... do stuff };(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); } // first is hello // second is world?
轉載于:https://www.cnblogs.com/myzy/p/7520794.html
總結
以上是生活随笔為你收集整理的ES6之主要知识点(二) 变量的解构赋值。默认值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转载] 中国象棋软件-引擎实现(一)概
- 下一篇: MySQL5.7.17的简单配置文件