ES6 学习笔记(二)解构赋值
本文最后更新于 541 天前,其中的信息可能已经有所发展或是发生改变。

一、数组的解构赋值

1、基本用法

ES6允许按照一定模式从数组和对象中提取值,然后对变量进行赋值,该操作即为解构
如:

let [a,b,c]=[1,2,3];
console.log(a,b,c) // a=1 b=2 c=3

let [foo,[[bar], baz]]=[1,[[2],3]];
console.log(foo,bar,baz) // foo=1  bar=2  baz=3

这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值
注意:
1、没有变量接收的解构值会被忽略掉。

let [a, [b], d] = [1, [2, 3], 4];
console.log(a,b,d) // a=1 b=2 d=3

2、如果赋值不是数组则会报错。

let [foo] = 1;
console.log(foo) // TypeError: 1 is not iterable

3、含有扩展运算符的解构

let a,b,c
[a,b,...c] = [1,2,3,4,5,6]
console.log(a,b,c); // a=1 b=2 c=[ 3, 4, 5, 6 ]

4、如果解构不成功,变量的值就等于undefined

let [bar, foo] = [1];
console.log(bar,foo)// bar=1  foo=undefined

5、只要某种数据接口具有Iterator(迭代器)接口,都可以采用数组形式的解构赋值

function* fibs() {  //Generator函数,原生具有Iterator接口。
    let a = 0;
    let b = 1;
    while (true) {
        yield a;
        [a, b] = [b, a + b];
    }
}
let [first, second, third, fourth, fifth, sixth] = fibs();
console.log(first, second, third, fourth, fifth, sixth);
// 输出:first=0  second=1  third=1  fourth=2  fifth=3  sixth=5

2、默认值

1、解构赋值允许指定默认值。

let [m, n = 'b'] = ['a', undefined];
console.log(m, n)// m=a  n=b

2、ES6内部使用严格相等运算符(===)判断一个位置是否有值,如果一个数组成员不严格等于undefined,默认值不会生效。

let [x = 1] = [undefined];
let [y = 1] = [null];
console.log(x, y)// x=1 y=null

3、如果默认值是一个表达式,会采用惰性求值,只有在用到时才会求值。

function f() {
    console.log("act");
    return 100;
}
let [x = f()] = [1];
console.log(x) // x=1

4、默认值可以引用解构赋值的其他变量,但该变量必须已经声明,否则会报错。

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

二、对象的解构赋值

对象的解构赋值与数组不同

1、数组的元素是按次序排列的,变量的取值是由它的位置决定。

let { bar, foo } = { foo: "aaa", bar: "bbb" };
console.log(bar, foo) // bar=bbb foo=aaa

2、对象的属性没有次序,变量必须与属性同名才能取到正确的值。

let { bar } = { foo: "aaa", bar: "bbb" };
console.log(bar)// bbb

3、如果变量名与属性名不一致,必须明确对应关系

let {foo: baz} = {foo:'aaa', bar:'bbb'};
console.log(baz)// aaa

4、对象解构赋值内部机制是先找到同名属性,然后再赋值给对应的变量,真正被赋值的是后者

let { bar, foo } = { foo: "aaa", bar: "bbb" };
console.log(bar, foo) // bar=bbb foo=aaa
let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };
console.log(bar, foo) // bar=bbb foo=aaa

注:foo(前)是匹配模式,foo(后)才是变量

对象的解构赋值的默认值

1、对象解构赋值也指定默认值,且默认值生效条件是对象的属性严格等于undefined

var { x, y = 5 } = { x: 1 };
console.log(x, y)// x=1 y=5

2、如果解构失败,变量的值等于undefined

let { foo } = { bar: 'bbb' };
console.log(foo) // 输出foo:undefined

3、如果解构模式是嵌套的对象,且子对象所在父属性存在,则会报错

let { foo: { bar } } = { baz: 'bbb' };
console.log(foo) // TypeError: Cannot destructure property `bar` of 'undefined' or 'null'.

4、如果要将一个已经声明的变量用于解构赋值,需要将解构赋值视为一个表达式,用括号括起来。如:

let x;
({ x } = { x: 1 });
console.log(x) // 1

5、对象解构赋值可以很方便地将现有对象的方法赋值给某个变量。

let { log, sin, cos } = Math;
console.log(Math.log(10)) // 输出:2.302585092994046

6、由于数组本质是特殊的对象,因此可以对数组进行对象属性的解构。

let arr = [1, 2, 3];
let { 0: first, [arr.length - 1]: last } = arr;
console.log(arr) // 输出arr=[ 1, 2, 3 ]

三、字符串的解构赋值

1、字符串的解构赋值,将字符串看作一个类似于数组的对象。

const [a, b, c, d] = 'hello';
console.log(a, b, c, d)// 依次输出:h e l l

2、类似数组的对象都有一个length属性,因此还可以对这个属性进行解构

let { length: len } = 'hello';
console.log(len) // 5

四、数值和布尔值的解构赋值

1、解构赋值的原则是,如果等号右边不是对象,则先转换为对象

let { toString: s } = 123;
console.log(s.call(100)); // 100

2、如果等号右边无法转换为对象,则会报错,如null和undefined。

五、函数参数的解构赋值

函数调用时,会将实参传递给形参,其过程就是实参赋值给形参。因此,也可以使用解构赋值。其规则与数组、对象的解构赋值一致,关键看参数是采用哪种解构赋值方式。

function add([x, y = 10]) {
    return x + y;
}
let z = add([1]);
console.log(z) // 11

六、解构赋值的用途

1、交换变量的值

let x = 1, y = 3;
[x, y] = [y, x];
console.log(x,y) // 3 1

2、从函数返回多个值

function func() {
    return [1, 2, 3];
}
let [a, b, c] = func();
console.log(a,b,c) // 依次输出:1 2 3

3、函数参数的定义
有序参数:

function f([x, y, z]) {
    return x*y*z
}
console.log(f([1, 2, 3])); // 6

无序参数:

function f({ x, y, z }) {
    return x * y * z
}
console.log(f({ z: 3, x: 1, y: 2 })); // 6

4、提取JSON数据

const json = '{"name":"TOM", "sex":"男", "age" : "18"}';
let data = JSON.parse(json);
let { name, age, sex: x } = data;
console.log(name, age, x); // 依次输出:TOM 18 男
本文链接:https://likepoems.com/articles/es6-learning-notes-for-deconstruction-assignment/
转载说明:本站文章若无特别说明,皆为原创,转载请注明来源:likepoems,谢谢!^^
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇