变量的解构赋值

2018-01-08  本文已影响0人  falcon_li

1.数组的解构赋值

1.1通过模式匹配,在对应的位置中对变量赋值;

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

1.2 解构不成功,值为 undefined

1.3 不完全解构,如果等号的右边不是数组(或者严格地说,不是可遍历的结构,参见《Iterator》一章),那么将会报错。

// 报错

let [foo] = 1;

let [foo] = false;

let [foo] = NaN;

let [foo] = undefined;

let [foo] = null;

let [foo] = {};

1.4 对于set 也可以进行组数的解构赋值

let [x, y, z] = new Set(['a', 'b', 'c']);

x // "a"

1.5 只要数据解构具有 Itetagor 接口,就可以进行解构赋值;

1.6 可以设置解构默认值

let [foo = true] = [];

foo // true

let [x, y = 'b'] = ['a'];// x='a', y='b'

let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'

注意,ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于undefined,默认值才会生效。

let [x = 1] = [undefined];

x // 1

let [x = 1] = [null];

x // null

null 不严格等于 undefined

1.7 默认值可以是已声明的其他解构赋值的变量;

let [x = 1, y = x] = [1, 2]; // x=1; y=2

let [x = y, y = 1] = []; // ReferenceError: y is not defined

2.对象的解构赋值

2.1 对象解构必须变量名与对象的属性同名;

let { bar, foo } = { foo: "aaa", bar: "bbb" };

foo // "aaa"

bar // "bbb"

let { baz } = { foo: "aaa", bar: "bbb" };

baz // undefined

2.2 如果变量名与对象的属性名不同;

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };

baz // "aaa"

let obj = { first: 'hello', last: 'world' };

let { first: f, last: l } = obj;

f // 'hello'

l // 'world'

2.3 对象解构也能设置默认值

    条件:对象的属性值严格等于 undefined

3. 字符串解构赋值

const [a, b, c, d, e] = 'hello';

a // "h"

b // "e"

c // "l"

d // "l"

e // "o"

字符串被转换成了一个类似数组的对象;

类似数组的对象都有一个 length 属性,所以

let {length : len} = 'hello';

len // 5

4. 数值和布尔值的赋值

4.1 解构赋值时,如果等号右边是数值或者布尔值。会先转换成对象:

let {toString: s} = 123;

s === Number.prototype.toString // true

let {toString: s} = true;

s === Boolean.prototype.toString // true

数值和布尔值的对象都有 toString 属性,所以变量 s 能够取到值;

解构的规则是,只要等号右边的值不是对象或者数组,就先转换为对象。由于 undefined 和 null 都无法转换为对象,所以都会报错;

let { prop: x } = undefined; // TypeError

let { prop: y } = null; // TypeError

5. 函数参数的解构赋值

5.1 传入参数时数组就被解构

function add([x, y]){

     return x + y;

}

add([1, 2]); // 3

[[1, 2], [3, 4]].map(([a, b]) => a + b);

// [3,7]

5.2 函数参数解构也可以设置默认值

function move({x = 0, y = 0} = {}) { return [x, y]; }

move({x: 3, y: 8}); // [3, 8]

move({x: 3}); // [3, 0]

move({}); // [0, 0]

move(); // [0, 0]

上面代码中,函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,x和y等于默认值。

注意,下面的写法会得到不一样的结果。

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]

上面代码是为函数move的参数指定默认值,而不是为变量x和y指定默认值,所以会得到与前一种写法不同的结果。

5.3 undefined 就会触发函数参数的默认值。

[1, undefined, 3].map((x = 'yes') => x);

// [ 1, 'yes', 3 ]

6 圆括号问题

6.1 es6 规定,只要可能导致解构歧义,就不得使用圆括号,所以建议只要有可能,就不要在模式中放置圆括号;

6.2 可以使用圆括号只有一种情况,赋值语句的非模式部分,可以使用圆括号;

[(b)] = [3]; // 正确

({ p: (d) } = {}); // 正确

[(parseInt.prop)] = [3]; // 正确

上面三行语句都可以正确执行,因为首先它们都是赋值语句,而不是声明语句;其次它们的圆括号都不属于模式的一部分。第一行语句中,模式是取数组的第一个成员,跟圆括号无关;第二行语句中,模式是p,而不是d;第三行语句与第一行语句的性质一致。

7 用途

7.1 交换变量的值

let x = 1;

let y = 2;

[x, y] = [y, x];

7.2 从函数返回多个值

// 返回一个数组

function example() { return [1, 2, 3]; }

let [a, b, c] = example();

// 返回一个对象

function example() { return { foo: 1, bar: 2 }; }

let { foo, bar } = example();

7.3 函数参数的定义

解构赋值可以方便地将一组参数与变量名对应起来。

// 参数是一组有次序的值

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

f([1, 2, 3]);

// 参数是一组无次序的值

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

7.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]

7.5 函数参数的默认值

jQuery.ajax = function (url, {

    async = true,

    beforeSend = function () {},

    cache = true,

    complete = function () {},

    crossDomain = false,

    global = true,

    // ... more config }) {

        // ... do stuff

};

指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句。

7.6 遍历 map

const 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

如果只想取键名或者键值

// 获取键名

for (let [key] of map) {

    // ...

}

// 获取键值

for (let [,value] of map) {

    // ...

}

7.7 输入模块的指定方法

加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰。

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

上一篇 下一篇

猜你喜欢

热点阅读