ES6对象,数组和解参数解构

对象解构

什么是解构

使用ES6的一种语法规则,将一个对象或数组的某个属性提取到某个变量中

const user = {
    name: "kevin",
    age: 11,
    sex: "男",
    address: {
        province: "四川",
        city: "成都"
    }
}

// 先定义5个变量,然后从对象中读取同名属性,放到变量中
let { name, age, sex, address, abc = 123 } = user

console.log(name, age, sex, address, abc)

解构不会对被解构的目标造成任何影响

在解构中使用默认值


{同名变量 = 默认值}

非同名属性解构


{属性名:变量名}
const user = {
    name: "kevin",
    age: 11,
    sex: "男",
    address: {
        province: "四川",
        city: "成都"
    }
}
// 先定义4个变量:name、age、gender、address
// 再从对象user中读取同名属性赋值(其中gender读取的是sex属性)
let { name, age, sex: gender = 123, address } = user

console.log(name, age, gender, address)


//解构出user中的name、province
//定义两个变量name、province
//再解构
const { name, address: { province } } = user;

console.log(name,  address, province)

数组结构

const number = ["a",'b','c','d']
const {
    0:n1,
    2:n2
}= number
console.log(n1,n2)

const [n1,n2]= number
console.log(n1,n2)

const numbers = ["a", "b", "c", "d"];
const [n1, , , n4, n5 = 123] = numbers;
console.log(n1, n4, n5)

//嵌套的数组
const numbers = ["a", "b", "c", "d", [1, 2, 3, 4]];
// 得到numbers下标为4的数组中的下标为2的数据,放到变量n中
const [, , , , [, , n]] = numbers;
console.log(n)

const numbers = ["a", "b", "c", "d", {
    a: 1,
    b: 2
}];
//得到numbers下标为4的数组的属性a,赋值给变量A
// const [, , , , { a: A }] = numbers;
const { a: A } = numbers[4];
console.log(A)


参数结构

function print({ name, age, sex, address: {
    province,
    city
} }) {
    console.log(`姓名:${name}`)
    console.log(`年龄:${age}`)
    console.log(`性别:${sex}`)
    console.log(`身份:${province}`)
    console.log(`城市:${city}`)
}

const user = {
    name: "kevin",
    age: 11,
    sex: "男",
    address: {
        province: "四川",
        city: "成都"
    }
}
print(user)

练习

1. const user = {
    name: "kevin",
    age: 11,
    sex: "男",
    address: {
        province: "四川",
        city: "成都"
    }
}

//解构出name,然后,剩余的所有属性,放到一个新的对象中,变量名为obj
// name: kevin
// obj : {age:11, sex:"男", address:{...}}

const { name, ...obj } = user;

console.log(name, obj)



2. const numbers = [324, 7, 23, 5, 3243];

// 得到数组前两项,分别放到变量a和b中,然后剩余的所有数据放到数组nums

// const [a, b, ...nums] = numbers;

const a = numbers[0], b = numbers[1], nums = numbers.slice(2);

console.log(a, b, nums);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力爬坑的小崔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值