最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why `const` value changed inside of `for...in` and `for...of` loop? - Stack Overflow

programmeradmin3浏览0评论

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.

As per MDN The value of a constant cannot change through re-assignment, and it can't be redeclared, so inside of for...in and for...of how is working?

const data = ['A', 'B', 'C', 'D'];

//Here const key is changed
for (const key in data) {
  console.log('key ',key);
}

//Here const value is changed
for (const value of data) {
  console.log('value ',value);
}

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.

As per MDN The value of a constant cannot change through re-assignment, and it can't be redeclared, so inside of for...in and for...of how is working?

const data = ['A', 'B', 'C', 'D'];

//Here const key is changed
for (const key in data) {
  console.log('key ',key);
}

//Here const value is changed
for (const value of data) {
  console.log('value ',value);
}

Share Improve this question edited Apr 6, 2018 at 19:29 Narendra Jadhav asked Apr 6, 2018 at 13:37 Narendra JadhavNarendra Jadhav 10.3k15 gold badges34 silver badges44 bronze badges 1
  • possible duplicate of scope rules of variables in for, for-in and for-of loops – Bergi Commented Apr 6, 2018 at 14:12
Add a comment  | 

3 Answers 3

Reset to default 10

Every iteration of a loop has its own block scope.

 for(let i = 0; i < 10; i++)
   setTimeout(() => console.log(i), 1);

That creates 10 seperate scopes, thats why it logs 10 different numbers. Therefore you can also declare constants in these different scopes.

The first three words of the material you quoted explains.

Constants are block-scoped

Each time you go around the for loop, you go to the top of a clean block. The first thing you do to it is to create a constant inside it.

In for-of-loop those constans are being declared for every iteration (in independent scopes), whereas in a for-loop you're re-using the variable, so you won't be able to re-assign values after its declaration.

Example with for-loop

const data = ['A', 'B', 'C', 'D'];

for (const i = 0; i < data.length; i++) {
  console.log('value ',data[i]);
}

发布评论

评论列表(0)

  1. 暂无评论