简体   繁体   English

迭代中的ES6 const用法

[英]ES6 const usage in iteration

I am reading Nodejs API, and I confused with iteration of buffer: 我正在阅读Nodejs API,我对缓冲区的迭代感到困惑:

for (const b of buf10) {
  console.log(b)
}

const is used to declare constants, so why use const instead of let ? const用于声明常量,那么为什么要使用const而不是let

Because b is a constant in the loop scope. 因为b 循环范围中的常量。 Remember that let and const have block scope in ES6. 请记住, letconst在ES6中具有块范围。 Every iteration does create a new variable which will stay constant in its scope. 每次迭代都会创建一个新变量,该变量将在其范围内保持不变。

const is used to declare constants, so why use const instead of let? const用于声明常量,那么为什么要使用const而不是let?

Because you can either use var let or const for declaration purpose however they behave differently. 因为您可以使用var letconst作为声明目的,但它们的行为不同。

In this case, 在这种情况下,

for (const b of buf10) {
  console.log(b)
}

Works because for each iteration you are getting a new const b and ending after the current iteration. 因为每次迭代都会得到一个新的const b并在当前迭代之后结束。

Concluding that if you know before hand that you are not going to modify the variable inside loop scope, you can go for it safely. 得出结论,如果你事先知道你不打算在循环范围内修改变量,你可以安全地去做。

You'll see an error if you try to modify the b inside the loop. 如果您尝试修改循环内的b则会看到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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