问题:
This question already has an answer here:
Javascript object bracket notation ({ Navigation } =) on left side of assign 4 answers
What is destructuring...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
This question already has an answer here:
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?