问题描述
我最近遇到了以下代码:
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对待const
和let
相同.我想知道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?
推荐答案
无论哪种方式,每次循环迭代都声明了一个新版本;这对于解决闭环问题很重要:
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.
选择let
或const
仅限于:
-
是否要在循环中为其分配新值?
Do you want to be able to assign it a new value within the loop?
您的个人风格偏好(或团队的偏好).
Your personal style preference (or your team's preference).
是的,除此之外,您还可以根据需要在循环内为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之间没有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!