首页 > 解决方案 > 在最新的 JavaScript 中,这个更短的符号是什么?

问题描述

我有这个:

const id = speakerRec.id;
const firstName = speakerRec.firstName;
const lastName = speakerRec.lastName;

我认为有类似的东西,但不记得了。

const [id, firstName, lastName] = speakerRec;

标签: javascriptobjectecmascript-6

解决方案


您需要{}用于解构对象属性:

const {id, firstName, lastName} = speakerRec;

[]用于数组解构:

const [one, two, three] = [1, 2, 3];

示范:

const speakerRec = {
  id: "mySpeaker",
  firstName: "Jack",
  lastName: "Bashford"
};

const { id, firstName, lastName } = speakerRec;

console.log(id);
console.log(firstName);
console.log(lastName);

const [one, two, three] = [1, 2, 3];

console.log(one);
console.log(two);
console.log(three);


推荐阅读