What do square brackets around an expression mean, e.g. `var x = a + [b]`?

后端 未结 7 1963
清酒与你
清酒与你 2020-12-04 12:00

We have received some JavaScript from an agency that looks wrong, but works.

For some reason they are adding square brackets ([, ]) around v

7条回答
  •  余生分开走
    2020-12-04 12:40

    Just in case anyone else arrives here while trying to find out what some weird/new syntax involving [square brackets] (seen in someone else's Javascript) might possibly be, like I was...

    Nowadays, with ES6, we also have [] used on the left-hand side for destructuring arrays, e.g.

    const names = ['Luke', 'Eva', 'Phil']; 
    const [first] = names;  
    console.log(first); // 'Luke' 
    const [first, second] = names;  
    console.log(first, second); // 'Luke' 'Eva'
    

    For further info see http://www.deadcoderising.com/2017-03-28-es6-destructuring-an-elegant-way-of-extracting-data-from-arrays-and-objects-in-javascript/ or google 'es6 destructuring'.

提交回复
热议问题