js 数组与对象的解构赋值
解构赋值是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 可以用来遍历对象属性进行解构赋值
重命名现象仅能使用于对象解构赋值,因为数组不存在名称