Skip to content

对象的解构赋值

对象的解构赋值等号两边必需同为对象类型,同时对象中的属性没有次序,所以不能像数组那样通过位置来决定变量的取值。要取到对象属性中的值,变量名必需与属性名同名。

模式(结构)匹配

等号两边必需同为对象类型

js
let {} = {};
// 或
let {} = [1, 3, 3];
// 或
let {} = new String("hello");

属性名相同完成赋值

对象解构赋值的内部机制是:先找对象中与变量名同名的属性名,然后再将对象对应的属性值赋值给到变量。

如果找不到同名的属性名,则变量名的默认值为 undefined

js
let { myname: _name, age: _age, sex: _sex } = { myname: "icoding", age: 3 };
console.log(_name, _age); // icoding 3 undefined
// 注意,上面并没有声明变量 name 和 age

如果变量名与属性名同名,可以采用简写形式

js
// 简写形式
let { myname, age } = { myname: "icoding", age: 3 };
console.log(myname, age); // icoding 3

// 上面代码,等价于下面代码
let { myname: myname, age: age } = { myname: "icoding", age: 3 };
console.log(myname, age); // icoding 3

区分模式与变量

用来接受对象属性值的才是新声明的变量。

js
// a,b是模式,匹配的是对象的属性  _a,_b是变量,用来接受属性的值
var { a: _a, b: _b } = { a: 1, b: 2 };
console.log(_a); // 1
console.log(_b); // 2
console.log(a); // a is not defined
console.log(b); // b is not defined

//  第一个foo是变量 第二个foo是匹配模式  第一个start是变量
let {
  foo,
  foo: { start },
} = { foo: { start: 33 } };
console.log(foo, start); // {start: 33} 33

复杂结构的嵌套取值

js
const obj = {
  x: 1,
  y: [2, 3, 4],
  z: { a: 5, b: 6 },
};

// 对象解构赋值
const {
  z,
  z: { b },
  y: [, , c],
} = obj;

console.log(z); // {a: 5, b: 6}
console.log(b); // 6
console.log(c); // 4

对象解构的默认值

对象解构时,如果变量的取值为 undefined 时,我们想为变量采用其它值,则就可以为变量指定默认值

js
let { a: _a = 0, b: _b = 0 } = { a: 1, b: 2 };
console.log(_a, _b); // 1 2

let { x: _x = 0, y: _y = 0 } = { x: 3 };
// _x 和 _y 解构取值为undefined,则会采用默认值
console.log(_x, _y); // 3 0

解构赋值的简写形式(为变量指定默认值)

js
let { a = "A", b = "B", c = "C" } = { a: 2, b: 3 };
console.log(a, b, c);

//   上面代码等价于;
let { a: a = "A", b: b = "B", c: c = "C" } = { a: 2, b: 3 };
console.log(a, b, c);

Released under the MIT License.