for ... of循环.我应该使用const还是let? [英] for...of loop. Should I use const or let?

查看:454
本文介绍了for ... of循环.我应该使用const还是let?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用for for循环时,这两个选项均允许并起作用:

When using a for of loop, both of these are allowed and work:

const numbers = [1,2,3];
// works
for(let number of numbers) {
    console.log(number);
}
// also works
for(const number of numbers) {
    console.log(number);
}

我总是使用const,因为我在任何上下文中都不会改变number变量,但是当我在其他人的代码中看到for...of循环时,通常会使用let.也许我没有看到const的缺点?浏览器错误?

I always use const since I annot fanthom changing the number variable in any context, but when I see a for...of loop in other people's code, it often uses let. Maybe there's a drawback to const that I didn't see? Browser bugs?

为什么要使用const,何时在for...of循环中使用let?

Why use const and when to use let in for...of loops?

推荐答案

为什么要使用const,何时在for...of循环中使用let?

Why use const and when to use let in for...of loops?

如果循环主体中没有分配给标识符,则基本上使用样式是使用let还是const.

If there are no assignments to the identifier within the loop body, it's basically a matter of style whether you use let or const.

如果希望循环体内的标识符是只读的,请使用const(例如,如果以后有人修改代码以添加分配,则在严格模式下这是一个主动错误).如果要分配给它,请使用let(因为您的代码中有分配,或者希望某人以后可以添加一个而不更改声明).

Use const if you want the identifier within the loop body to be read-only (so that, for instance, if someone modifies the code later to add an assignment, it's a proactive error in strict mode). Use let if you want to be able to assign to it (because you have an assignment in your code, or you want someone to be able to add one later without changing the declaration).

您可以使用for-offor-in循环执行此操作. for循环的控制变量不能为常量,因为它已在for循环的"update"子句中进行了修改.

You can do this with for-of and for-in loops. A for loop's control variable must not be constant, because it gets modified in the for loop's "update" clause.

为清楚起见,这是一个在循环体内分配的示例:

For clarity, here's an example with an assignment within the loop body:

"use strict";
for (let str of ["a", " b", " c "]) {
    str = str.trim();
//  ^^^^^----- assignment to the identifier
    console.log(`[${str}]`);
}

如果在上面的str中将const用作str,则会出现错误:

If you use const for str in the above, you get an error:

"use strict";
for (const str of ["a", " b", " c "]) {
    str = str.trim();
//  ^^^^^----- Error
    console.log(`[${str}]`);
}

这篇关于for ... of循环.我应该使用const还是let?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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