ES6之主要知识点(二) 变量的解构赋值。默认值
生活随笔
收集整理的這篇文章主要介紹了
ES6之主要知识点(二) 变量的解构赋值。默认值
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
引自http://es6.ruanyifeng.com/#docs/destructuring
- 數(shù)組解構(gòu)賦值
- 默認(rèn)值
- 對(duì)象解構(gòu)賦值
- 用途
1.數(shù)組的解構(gòu)賦值
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 // []因?yàn)榈忍?hào)右邊的值,要么轉(zhuǎn)為對(duì)象以后不具備 Iterator 接口(前五個(gè)表達(dá)式),要么本身就不具備 Iterator 接口(最后一個(gè)表達(dá)式)。
2.默認(rèn)值?
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.對(duì)象的解釋構(gòu)?
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)從函數(shù)返回多個(gè)值
// 返回一個(gè)數(shù)組 function example() {return [1, 2, 3]; } let [a, b, c] = example();// 返回一個(gè)對(duì)象 function example() {return {foo: 1,bar: 2}; } let { foo, bar } = example();(3)函數(shù)參數(shù)的定義
// 參數(shù)是一組有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]);// 參數(shù)是一組無(wú)次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});(4)提取JSON數(shù)據(jù)
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)函數(shù)參數(shù)的默認(rèn)值
jQuery.ajax = function (url, {async = true,beforeSend = function () {},cache = true,complete = function () {},crossDomain = false,global = true,// ... more config }) {// ... do stuff };(6)遍歷Map結(jié)構(gòu)
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?
轉(zhuǎn)載于:https://www.cnblogs.com/myzy/p/7520794.html
總結(jié)
以上是生活随笔為你收集整理的ES6之主要知识点(二) 变量的解构赋值。默认值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [转载] 中国象棋软件-引擎实现(一)概
- 下一篇: MySQL5.7.17的简单配置文件