This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign

(4个答案)



What is destructuring assignment and its uses?

(3个答案)


去年关闭。




let messages = {
  1: {
    id: '1',
    text: 'Hello World',
    userId: '1',
  },
  2: {
    id: '2',
    text: 'By World',
    userId: '2',
  },
};

// what does this statement do?
const {
  [1]: message,
  ...otherMessages
} = messages;

console.log("other messages: ", otherMessages);


我们没有变量otherMessages,那么其余语法如何在该变量上工作?上面的语句总体上做了什么,有点复杂?

最佳答案



=符号的左侧,您声明要解构的变量,在右侧声明要解构的变量。

为此,您要声明两个变量messageotherMessages:

const { [1]: message, ...otherMessages } = messages;

然后您将1键的值提取到message中,其余messages对象将分解为otherMessages

由于messages包含两个具有键12的条目,因此otherMessages将是一个包含其余键的对象,该键仅是2

09-25 16:54