为什么JavaScript const可以在for循环中很好地工作 [英] Why JavaScript const works well with for in loop

查看:428
本文介绍了为什么JavaScript const可以在for循环中很好地工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么JavaScript constfor in循环中与let相同? const用于在EC6中声明常量.那么为什么const num的值在for in的每次迭代中都会更新?

Why JavaScript const works same as let in for in loop? const is using to declare constants in EC6. Then why the const num value getting updated in each iteration of the for in?

与let配合使用

for (let num in nums) {
    console.log(num); // works well, as usual
}

用于const

for (const num in nums) {
    console.log(num); // why const value getting replaced
}

推荐答案

为什么JavaScript const的作用与让in for in循环相同?

Why JavaScript const works same as let in for in loop?

根据定义,const的作用域类似于let.

By definition, const is block scoped like let.

那为什么在for in的每次迭代中都会更新const num值?

Then why the const num value getting updated in each iteration of the for in?

不是.由于它是块作用域的,因此每次循环时,旧常量都会超出作用域,并创建一个新的常量.

It isn't. Since it is block scoped, each time you go around the loop the old constant drops out of scope and you create a new one.

这篇关于为什么JavaScript const可以在for循环中很好地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆