在声明方面,let和const在for循环内的const之间没有区别吗? [英] Is there no difference between let and const inside for of loop in Javascript in terms of declaration?

查看:129
本文介绍了在声明方面,let和const在for循环内的const之间没有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了以下代码:

I recently came across this code:

for (const temp of [1,2]) {
  // do something
}

我认为最好将let声明用于temp,因为这样可以将变量仅声明一次.但是,我还通过babel运行了该示例以及let的版本,这是我看到的:

I thought that it'd be better to use let declaration for temp because this way the variable would be declared only once. However, I also ran this example as well as the version with let through babel and this is what I see:

for (const p of [1,2]) {

}

for (let s of [1,2]) {

}

成为:

for (var _i = 0, _arr = [1, 2]; _i < _arr.length; _i++) {
  var p = _arr[_i];
}

for (var _i2 = 0, _arr2 = [1, 2]; _i2 < _arr2.length; _i2++) {
  var s = _arr2[_i2];
}

因此babel对待constlet相同.我想知道Javascript运行时是否在后台相同地对待这两个版本.这样的结论是,即使在循环内用let声明了变量,每次迭代仍会重新声明该变量?

So babel treats const and let identically. I'm wondering if Javascript runtime treats the 2 versions identically under the hood. Is the conclusion of this is that even if a variable is declared with let inside the loop it will still be redeclared on each iteration?

推荐答案

我认为最好将temp用作let声明,因为这样只能将变量声明一次.

I thought that it'd be better to use let declaration for temp because this way the variable would be declared only once.

无论哪种方式,每次循环迭代都声明了一个新版本;这对于解决闭环问题很重要:

There's a new version declared for each loop iteration either way; this is important for addressing the closures-in-loops problem:

const array = [1, 2, 3, 4];
for (const entry of array) {
    setTimeout(() => {
        console.log(entry);
    }, 0);
}

如果没有为每次循环迭代创建一个新变量,则它将记录相同的值(大约4个)四次.

If there weren't a new variable created for each loop iteration, that would log the same value (probably 4) four times.

选择letconst仅限于:

  1. 是否要在循环中为其分配新值?

  1. Do you want to be able to assign it a new value within the loop?

您的个人风格偏好(或团队的偏好).

Your personal style preference (or your team's preference).

我想知道Javascript运行时是否在后台相同地对待这两个版本.

I'm wondering if Javascript runtime treats the 2 versions identically under the hood.

是的,除此之外,您还可以根据需要在循环内为let变量分配一个新值.¹例如:

Yes, other than that you can assign the let variable a new value within the loop if you like.¹ For instance:

const strings = ["a", "b", "c"];
for (let str of strings) {
    str = str.toUpperCase();
    console.log(str);
}

例如,唯一的区别是变量是否可变.

E.g., the only difference is whether the variable is mutable or not.

¹为避免疑问:分配给它的所有操作都是更改该变量的值.

这篇关于在声明方面,let和const在for循环内的const之间没有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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