简体   繁体   中英

es6 iterate object with var, let, or const?

Traditionally, we use

for (var key in yourobject) {
  console.log(key, yourobject[key]);
}

But with es6, should I change to using const key or let key instead?

This has nothing to do with whether you're using them in a loop. Use the correct binding for whatever your program needs

  • const bindings cannot be reassigned
  • let bindings can be reassigned

If you do not need the ability to reassign your variables, use const – it's more strict and will help protect you from accidental reassignment

If you do need the ability to reassign, you have no other choice but to use let (or var )


I like @jfriend's decision tree, but I might write mine like this ^_^

  1. use const
  2. if you run into a reassignment problem, use let
  3. if you run into an out-of-scope problem, double-check you haven't made a mistake; if not, use var

so since i'm using it in a for loop which reassigns the key in each cycle, i should use let?

No. const and let bindings are only available within the context/scope they are defined. In the case of for or while loops, the binding will only be available in the loop's body – no reassignment is taking place

 for (const x of [1,2,3]) console.log(x) //1 //2 //3 for (const {a} of [{a:1}, {a:2}, {a:3}]) console.log(a) //1 //2 //3 // const x and const a are not available outside of the loop console.log(x) // ERROR: Uncaught ReferenceError: x is not defined console.log(a) // ERROR: Uncaught ReferenceError: a is not defined 

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