简体   繁体   中英

How to mix const and let when using object or array destructuring assignment in ES6?

Example :

const foo = {a: "A", b: "B"}
const {a, b} = foo

What if I want b to be a variable using let ?

It seems like you can't differentiate variable's declaration in a one line. However, you could split it into two lines and use a different variable declaration, depends on which variable you want to get.

const { a } = foo; 
let { b } = foo;

If you want to use array destructuring assignment with const and let you can use elision. Let's consider an example:

const [a, b, c] = foo;

If you want to 'a' be a let, and 'b' and 'c' const, you can write:

let [ a ] = foo;
const [, b, c] = foo;

Another way is to use the fact that array is an object. So you can write it also like this:

let [a] = foo;
const {1: b, 2: c} = foo;

All about destructing can be find here: http://exploringjs.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM