js 解构赋值

1. 数组的解构赋值

// 对不需要的值,使用',',将该该值略过。
const [first, , third, ...rest] = [1, 2, 3, 4, 5];
console.log(first) // 1
console.log(third) // 3
console.log(rest)  // [4, 5]

const [a, b = 'default'] = []
console.log(a,b) // undefined 'default'

String、Set、Map等所有可遍历对象都能采用解构赋值

// String
const [A,B,C,D] = 'abcd'
console.log(A,B,C,D) // a b c d

// Set
const[one, two, three, four] = new Set([1, 2, 3, 4])
console.log(one,two,three,four) // a b c d

2.对象的解构赋值

let info = {
  name:"David",
  age: 24,
  weight: 180
};
// 1.同样使用'='赋予默认值 2.变量名可通过解构重新赋予新的名称
let { name, age = 18, weight:height } = info;
console.log(name, age, height) // David 24 180

// 2.仅取部分变量
let { name: nickname, ...rest } = info;
console.log(nickname, rest) // David {age: 24, weight: 180}

// 3.嵌套层级较多的情况,只需对应好顺序及层级即可正确解构
let cellPhone = {
	size: {
		width: 375,
		height: 667
	},
	package: ['type1', 'type2'],
	price: 8888,
};

let { size: {width, height: weight }, package: [, t2 ], price } = cellPhone;
console.log(weight, t2) // 667 "type2"

通过解构赋值改变对象的属性值

const obj = {a: '123', b: '456'};
[obj.a, obj.b] = ['aaa', 'bbb'];
console.log(obj); // {a: "aaa", b: "bbb"}

在for…of中使用

const obj = {a: '123', b: '456'};
for (let [k, v] of Object.entries(obj)) {
	console.log(k, v)
}

// a '123'
// b '456'
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值