JS destructuring complicated statement? [duplicate]

问题: This question already has an answer here: Javascript object bracket notation ({ Navigation } =) on left side of assign 4 answers What is destructuring...

问题:

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);

We didn't have a variable otherMessages, so how does the rest syntax work on this variable? What does the above statement do in general, it's somewhat complicated?


回答1:

This is a destructuring assignment. See MDN fore more information

On the left side of the = sign, you declare the variables to be destructured, and on the right side the variable to desctructure.

Doing this, you are declaring two variables message and otherMessages:

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

and you are extracting the value of key 1 into message, and the rest of the messages object will be desctructured into otherMessages.

Since messages contains two entries with keys 1 and 2, otherMessages will be an object containing the remaining keys, which is only key 2.


回答2:

When trying to assign the variable otherMessages, the runtime checks to see where it is declared. As it goes up the scopes if it reaches the top level, in this case window, it will declare the variable and then assign to it using the destructuring syntax.

Think about this another way: if you were to do something like this:

otherMessages = [1, 2]

Without declaring otherMessages as a var before hand, wouldn’t the runtime declare the variable for you?

  • 发表于 2019-03-11 03:23
  • 阅读 ( 236 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除