解构赋值

解构赋值

概述

在 ES6 中新增了变量赋值的方式:解构赋值。允许按照一定模式,从数组和对象中提取值,对变量进行赋值。

注意:
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。

数组解构赋值

例子:

// 数组解构赋值 ----------------
let arr = [1, 2, 3]
let aa = arr[0]
let bb = arr[1]
let cc = arr[2]
console.log(aa, bb, cc);
// ES6
let [aa1, bb1, cc1] = [1, 2, 3]
console.log(aa1, bb1, cc1);

// 1.赋值元素可以是任意可遍历的对象
let [aa2, bb2, cc2] = "abc"   // ["a","b","c"]
let [one, two, three] = new Set([1, 2, 3])
console.log(aa2, bb2, cc2);
console.log(one, two, three);
// 2.左边的变量(`)[]
let user1 = {};
[user1.firstName, user1.secondName] = 'Kobe Bryant'.split(' ')
console.log(user1.firstName, user1.secondName) // Kobe Bryant
// 3.循环体
let user2 = {
    name: 'json',
    age: 30
}
for (let [key, value] of Object.entries(user2)) {
    console.log(`${key}:${value}`);
}

let user3 = new Map()
user3.set('name', 'John')
user3.set('age', '30')
for (let [key, value] of user3.entries()) {
    console.log(`${key}:${value}`);
}

// 4.可以跳过赋值元素
// second element is not needed
let [name, , title] = ['john', 'Jim', 'Sun', 'Moon']
console.log(title); // Sun
// 5.rest 参数
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]

console.log(name1); //Julius
console.log(name2); //Caesar
// Note that type of `rest` is Array
console.log(rest[0]);
console.log(rest[1]);
console.log(rest.length);
// 6.默认值
let [firstName, surname] = []
console.log(firstName);
console.log(surname);
// default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"]
console.log(name);
console.log(surname);
// ----------------

这种写法属于"模式匹配",等号两边的模式相同,左边的变量就会被赋予对应的值。
结构成功就赋值,不成功的变量值等于undefined。解构赋值不需要全部成功,只匹配一部分,解构也能成功。

重点:只要某种数据结构具有Iterator接口,都可以采用数组形式的解构。
// 1.可跳过赋值元素
// 2.rest 参数  例: let[a,b,...rest]=[1,2,3,4,5,6]
// 3.默认值,如果数组的内容少于变量的个数,并不会报错,没有分配到内容的变量会是 undefined

对象解构赋值

例子:

// 对象解构赋值 +++++++++++++
// 1.基本用法 let {var1,var2}={var1:...,var2:...}
let options = {
    title: "Menu",
    width: 100,
    height: 200
}
let { title, width, height } = options
console.log(title, width, height);    //Menu 100 200
// 想使用其他变量名,属性一致,但顺序不影响
let { width: w, height: h, title: t } = options
console.log(w, h, t); // 100 200 Menu
// 2.默认值
let options2 = {
    title: "Menu"
}
let { width = 100, height = 200, title } = options2
console.log(title, width, height);
// 3.rest 运算符
let options = {
    title: "Menu",
    height: 200,
    width: 100
}
let { title, ...rest } = options
// now title="Menu",rest={height:200,width:100}
console.log(rest.height, rest.width);
// 4.嵌套对象
let options = {
    size: {
        width: 100,
        height: 200
    },
    items: ["Cake", "Donut"],
    extra: true     // something extra that we will not destruct
}
// destructuring assignment on multiple lines for clarity
let {
    size: {
        width,
        height
    },
    items: [item1, item2],
    title = "Menu"  // not present in the object (default value is used)
} = options
console.log(title, width, height, item1, item2);
// ++++++++++++++
  • 在这个结构赋值的过程中,左侧的“模板”结构要与右侧的 Object 一致,但是属性的顺序无需一致。
  • 可以自定义变量名
  • 默认值,赋值过程中可以指定默认值,解构失败值为undefined
  • rest运算符,作用和数组解构赋值的一样

字符串解构赋值

例子:

// 字符串解构赋值 ----------
let str = "imooc"
let [a, b, c, d, e] = str
console.log(a, b, c, d, e);
// --------------

数值和布尔值的解构赋值

例子:

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

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

解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。数值和布尔值的包装对象都有toString属性,因此变量s都能取到值。

函数参数的解构赋值

// 函数参数的解构赋值
function add([x, y]) {
    return x + y;
}
add([1, 2]); // 3

注意点

  • 如果要将一个已经声明的变量用于解构赋值,需注意符号
let x;
// 不写圆括号,JavaScript 引擎会将{x}理解成一个代码块
({x} = {x: 1});
  • 解构赋值允许等号左边的模式之中,不放置任何变量名。
  • 由于数组本质是特殊的对象,因此可以对数组进行对象属性的解构。
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
//数组arr的0键对应的值是1,[arr.length - 1]就是2键,对应的值是3。方括号这种写法,属于“属性名表达式”

资料来源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值