js 数组与对象的解构赋值

本文介绍了JavaScript中的解构赋值技术,包括如何从数组和对象中提取值并分配给不同变量。此外,还提到了使用for、for of、for each遍历数组进行解构赋值,以及利用for in遍历对象属性。同时,文章指出重命名特性只适用于对象解构赋值,因数组元素无名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解构赋值是javascript 语法,作用是将值从数组、或属性从对象,提取到不同的变量中。

1. 数组解构
		1.1 声明变量并赋值:
			let hi = ['hello', 'world'];
			let [hello, world] = hi
			console.log(hello) => hello
			console.log(world) => world
			
		1.2 设置解构默认值
			let hi = 'hello world';
			let [hello, world = 'hi'] = hi
			console.log(hello) => hello world
			console.log(world) => hi
			
		1.3 使用扩展运算符解构
			function f () {
				return ['hello', 'world', 'my', 'name', 'is Lilei'];
			}
			let [hello, world, ...who] = f()
			console.log(hello) => hello
			console.log(world) => world
			console.log(who) => ['my', 'name', 'is Lilei']
			
		1.4 忽略某些返回值
			function f () {
				return ['hello', 'world', 'my', 'name', 'is Lilei'];
			}
			let [hello, world,, ...who] = f()  // 两个逗号之间的值被忽略了
			console.log(hello) => hello
			console.log(world) => world
			console.log(who) => ['name', 'is Lilei']
2. 对象解构
		2.1 基本解构
			let obj = {
				hello: 'hello',
				world: 'world'
			}
			let {hello, world} = obj
			console.log(hello) => hello
			console.log(world) => world
		
		2.2 属性重命名
			let obj = {
				hello: 'hello',
				world: 'world'
			}
			let {hello: one, world: two} = obj;
			console.log(one) => 'hello'
			console.log(two) => 'world'

		2.3 默认值
			let obj = {
				hello: 'hello'
			}
			let {hello, world = 'world'} = obj
			console.log(hello) => hello
			console.log(world) => world
			
		2.4 重命名与默认值同时存在
			let obj = {
				hello: 'hello'
			}
			let {hello: one, world:two = 'world'} = obj
			console.log(one) => hello
			console.log(two) => world

		2.5 为函数参数设置默认值
			function f ({name='Tim', hi={hello: 'hello', world: 'world'}, age: 18} = {}) {
				console.log(name + ':' + hi + ':' + age)
			}
			f({
				name: 'Tom',
				age: 20
			})
	
		2.6 对象展开运算符
			let obj = {
				hello: 'hello',
				world: 'world',
				name: 'Tim',
				age: 18
			}
			let {hello, world, ...hi} = obj;
			console.log(hello) => hello
			console.log(world) => world
			console.log(hi) => {name: 'Tim', age: 18}

补充说明:
        for 、 for of 、 for each 可以用来遍历数组进行解构赋值
        for in 可以用来遍历对象属性进行解构赋值
        重命名现象仅能使用于对象解构赋值,因为数组不存在名称

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值