javascrpt 解构赋值

数组解构

扁平数组:

let [a,b,c] = [1,2,3]
console.log(a,b,c) 	// 1 2 3

复杂数组:

let [a, [b,c]] = [1, [2,3]]
console.log(a,b,c)	// 1 2 3

将多个元素赋给一个变量

let [a, , ...rest] = [1,2,3,4,5]	// 中间空一个元素不赋值
console.log(a, rest)		// 1  [3,4,5]

给变量设置默认值

let [a = 'ooops', b = 'ooops', c = 'ooops'] = [2, , 4]
console.log(a,b,c)		// 2 'ooops' 4

交换两个数

let x = 1, y = 2
[x, y] = [y, x]
console.log(x, y) 	// 2 1

对象解构

对象解构是根据 key 值来进行赋值的,如果没有对应的 key, 那么会赋值 undefined

let man = {
	name: 'romeo',
	age: '23',
	prop: 'handsome',
}

let {name, age, prop} = man
console.log(name, age, prop);	// romeo 23 handsome

let {name, age, prop: appearance} = man
console.log(name, age, appearance);	// romeo 23 handsome

同样也有多个键值对赋值给一个变量

let {a, ...rest} = {a:1, b:2, c:3}
console.log(a)	// 1
console.log(rest) // {b: 2, c: 3}

猜你喜欢

转载自blog.csdn.net/romeo12334/article/details/84965293
今日推荐