js复习:几个例子弄懂解构赋值


前言

复习啊复习,js的基础都快忘完了,时不时捡起来再看看。


一、概念

解构赋值语法是一种 Javascript 表达式。通过解构赋值, 可以将属性/值从对象/数组中取出,赋值给其他变量。

二、例子

1.声明时解构

	const arr = ['haha','xixi','hehe']
	const [a,b,c] = arr
	console.log(a)  //haha
	console.log(b)  //xixi
	console.log(c)  //hehe

解释:将数组中的三个值取出来,赋值给a,b,c三个变量

2.剩余参数解构

	const arr = ['haha','xixi','hehe']
	const [a,...rest] = arr
	console.log(rest)  //["xixi","hehe"]

解释:使用rest语法收集剩余参数,变量rest输出剩下的数值为一个数组

3. 默认值

	const arr = ["haha",'xixi']
	const [a,b,c="hehe"] = arr
	console.log(c)  //hehe

解释:为防止从数组中抽出空值,可以在解构时使用等号提前赋一个默认值

4.解构对象

	const obj = {
		name : "xixi",
		age : 18
	}
	const {name,age} = obj
	console.log(name)  //xixi
	console.log(age)  //18

解释:从对象里抽取属性为name,将值赋值给name变量

5.解构时的重命名

	const obj = {
		name : "xixi",
		age : 18
	}
	const {name : xName} = obj //重命名
	console.log(xName)  //xixi

解释:解构对象时使用冒号,将属性值赋值给一个新变量

6.嵌套解构

	const obj = {
		parent : {
			child : "xixi"
		}
	}
	const { parent : { child } } = obj //嵌套解构
	console.log(child) //xixi

解释:当出现嵌套时,可以使用多级解构直接将属性值提取出来

7.遍历对象值时的解构

	const stu = [
		{ id: 1},
		{ id: 2},
		{ id: 3},
	]
	for (let {id} of stu){
		console.log(id)  //循环输出 1 2 3
	}

解释:在遍历对象时使用解构,依次将属性值遍历出来

8.函数参数解构

	const stu = {id:0, name:"xixi"}
	function fun({id,name}){
		console.log(name)  //xixi
	}
	fun(stu)

解释:取出对象属性作为参数传递值

9.变量交换

	let a = "xixi";
	let b = "haha"; //这里要必须要有分号结尾,否则js认为这一句的"haha"和下一句[a,b]是连在一起的
	
	[a,b] = [b,a];
	console.log(a);  //haha
	console.log(b);  //xixi

注意: 这样解构时需要前一语句必须要有分号结尾,否则会报错。

10.使用正则时的解构

	var re = /\w+\s/g;
	var str = "all over the world"
	
	const [a,b,c,d] = str.match(re)
	console.log(a,b,c,d)  //输出all over the undefined

解释:使用正则表达式将str可以匹配到的值赋值给a,b,c。有人问为什么d是undefined?因为world没有匹配到。

11.es6计算属性的解构

	const attrName = "name"
	const obj = {
		[attrName]:"xixi"
	}
	const {[attrName]:myName} = obj
	console.log(obj[attrName])  //xixi
	console.log(obj["name"]) //xixi
	console.log(myName)  //xixi

解释:es6中的对象属性也可以是一个变量,因此obj[“name”]也可以输出属性值,也可以单独为其赋值新变量。


# 参考
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值