es6 解构对象为数据_javascript-es6中对象和数组解构(笔记)

56e94bac83aacc20823329d6bd7bb24e.png

解构可以帮助我们更好提取需要的对象中的数据,es6中可以使用新特性来更好的完成解构。

1. 对象解构

var car = {name:'baoma',color:'red'}
let {name,color} = car
// name :baoma
// color:red
//对象不能赋值为null或者undefiend
//TypeError: Cannot destructure property `type` of 'undefined' or 'null'.

解构的时候可以给解构的参数,重新命名,像这样,冒号后面就是对应的变量名

let {type:t} = {type:4}
console.log(t)

多重嵌套时的结构

// 多重嵌套 命名
// 这里 从a中取b命名为c
let {a:{b:c}} = {a:{
    b:5
}}
console.log(c)

2. 数组解构

// 数组结构
let [color1,color2] = ['red','yellow']
console.log(color1,color2)

想要获取特定位置的元素的话,可以把特定位置空出来,像这样

let [,color2,color3] = ['red','yellow','blue']

同样,对于已经申明的变量,数组是这样解构的

//对于已经声明的变量
let color3 = 'red';
[color3] = ['blue']
console.log(color3)

数组中不定参数的解构

//不定参数的解构
let [first,...more]=[1,2,3,4,5];
console.log(first,more)

3. 举例

//交换两变量中的值,
let e=1,f=2;
[e,f] = [f,e];
console.log(e,f)

//克隆数组
let needCopyArray = [1,2]
let [...copyArray] = needCopyArray;
console.log(copyArray);

4.完整代码

// 不允许为空,或者undefined
//let { type } = null;
// 变量命名
let {type:t} = {type:4}
console.log(t)
// 多重嵌套 命名
let {a:{b:c}} = {a:{
    b:5
}}
console.log(c)

// 数组结构
let [color1,color2] = ['red','yellow']
console.log(color1,color2)

//对于已经声明的变量
let color3 = 'red';
[color3] = ['blue']
console.log(color3)

//不定参数的解构
let [first,...more]=[1,2,3,4,5];
console.log(first,more)

//交换两变量中的值,
let e=1,f=2;
[e,f] = [f,e];
console.log(e,f)

//克隆数组
let needCopyArray = [1,2]
let [...copyArray] = needCopyArray;
console.log(copyArray);

// 数组结构
let [color1,color2] = ['red','yellow']
console.log(color1,color2)

//对于已经声明的变量
let color3 = 'red';
[color3] = ['blue']
console.log(color3)

//不定参数的解构
let [first,...more]=[1,2,3,4,5];
console.log(first,more)

//交换两变量中的值,
let e=1,f=2;
[e,f] = [f,e];
console.log(e,f)

//克隆数组
let needCopyArray = [1,2]
let [...copyArray] = needCopyArray;
console.log(copyArray);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值