变量的解构赋值

变量的解构赋值

数组的解构赋值

基本方法

let a = 1;
let b = 2;
let c = 3;

//es6 解构
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 // []

有默认值的解构赋值

let [foo = true] = [];
foo // true

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

只有当赋值为undefined时才会使用默认值,null时不会

let [x = 1] = [undefined];
x // 1

let [x = 1] = [null];
x // null

默认值为表达时 只有用到时才会求值

function f() {
  console.log('aaa');
}

let [x = f()] = [1];  //f()不执行

对象解构赋值

对象的结构赋值

let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"  属性名必须完全相同

属性名不同的解构赋值

let { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined

嵌套赋值

let obj = {
  p: [
    'Hello',
    { y: 'World' }
  ]
};

let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
p // ["Hello", {y: "World"}]

对于已经声明的变量 为了防止解析时当做一个代码块 必须在外面加上括号

// 正确的写法
let x;
({x} = {x: 1});

字符串解析赋值

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

数值和布尔值的解析赋值

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

函数参数的解构赋值

用法

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3
原传入一个数组 解构赋值为几个变量

如果要对已经声明的变量进行解构赋值的话 要使用圆括号

[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值