Syntax - what does square brackets around a variab

2019-02-27 21:49发布

问题:

This question already has an answer here:

  • Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean? 4 answers

Take the following line of code

const [component] = router.getMatchedComponents({ ...to })

Could anyone advise what the square brackets around component means here? I have tried to google this but struggling to find an answer

回答1:

It's called Destructuring assignment, and it's used to unpack the values of an array and assign them to new variables.

So here in your code:

const [component] = router.getMatchedComponents({ ...to })

You are declaring a component variable that will hold the object hold in the array that will be returned from router.getMatchedComponents({...to}), where to is an array like structure turned into array using the spread operation.