码迷,mamicode.com
首页 > 其他好文 > 详细

学些ES6:Destructuring

时间:2015-08-30 12:44:59      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

Destructuring:

数组:

let [firstValue] = [1]; // firstValue: 1

let c, d;
let [a, b] = [c, d] = [1, 2];

var [head, ...tail] = [1, 2, 3, 4]; // tail: [2,3,4]

可以交换变量:

let [x, y] = [‘ax‘, ‘why‘];
[x, y] = [y, x]; // x: why, y:ax

const all = [‘ax‘, ‘why‘, ‘zet‘];
const [,,z] = all; // z: set

嵌套数组也可以:

const user = [[‘Some‘, ‘One‘], 23];
const [[firstName, surname], age] = user;

for (var [a, b] of [[1, 2]]) {} // a:1, b:2

字符串也可以哦:

let [a, b, c] = ‘abc‘; // [a, b, c]: [‘a‘, ‘b‘, ‘c‘]

object:

const {t: x} = {t: 1, b:2}; // x:1

const {x} = {x: 1, b:2}; // x:1

const m = {first: 23, second: 42};
const {magic: {second: second}} = {magic: m}; // second: 42

const {z:[,x]} = {z: [23, 42]}; // x:42

const [,[{lang: lang}]] = [null, [{env: ‘browser‘, lang: ‘ES6‘}]]; // lang: es6

包括prototype:

const {substr} = "1"; // substr: String.prototype.subst

默认值:

const [,b=2] = [1,,3]; // b:2

const {a, b=2} = {a: 1, b: undefined}; // b:2

const {a, b=2} = {a: 1};

const {x: y=42} = {y: 23}; // y: 42

参数处理:

const fn = ({id, name}) => {
// ...
};

const user = {name: ‘Wolfram‘, id: 42};
fn(user); // id: 42, name: Wolfram

const fn = ([,{name}]) => {
// ...
};
const users = [{name: ‘nobody‘}, {name: ‘Alice‘, id: 42}];
fn(users); // name: alice

同样可以使用默认值:

const fn = (id, name=‘Bob‘, c) => {
// ...
};
fn(23, undefined, 3); // id:23, name: Bob, c:3

const fn = (id, name=‘Bobby‘) => {
// ...
};
fn(23, ‘Bob‘); // id:23, name: Bob

const defaultUser = {id: 23, name: ‘Joe‘};
const fn = ([user=defaultUser]) => {
// ...
};
fn([]); // user: defaultUser

const fn = (id=1, [arr], {obj=2}) => {
// ...
};
fn(void 0, [2], {obj:3}); // id: 1, arr: 2, obj: 3

学些ES6:Destructuring

标签:

原文地址:http://www.cnblogs.com/benben77/p/4770582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!