在javascript for循环中'let'vs'var',是否意味着使用'var i = 0'的所有for循环实际上应该是'let i = 0'而是? [英] 'let' vs 'var' in javascript for loops, does it mean that all the for loops using the 'var i =0' should actually be 'let i =0' instead?
问题描述
根据使用let之间的区别是什么?和var要声明一个变量?,当在for循环中使用时,let关键字的范围小于var。这是否意味着'for(var i = 0 ...'的实际正确方法应该使用let的所有地方?我无法想象一个开发人员正在使用'for(var i = 0)的情况......'希望var i仍然可以在for循环之外看到,这意味着所有'for(var i = 0 ...'都是错的,正确的方法是'for(让i = 0 ... '?只是一个是或否的问题。
Since according to What's the difference between using "let" and "var" to declare a variable?, the let keyword has a smaller scope than var when used in a for loop. Does this mean that of all the places where 'for (var i=0...' the actual correct way should be to use let? I can't imagine a case where a developer who was using 'for (var i=0...' would want to have the var i still be visible outside the for loop, meaning that all 'for (var i=0...' are wrong and the correct way is 'for (let i=0...'? Just a yes or no question.
function allyIlliterate() {
//tuce is *not* visible out here
for( let tuce = 0; tuce < 5; tuce++ ) {
//tuce is only visible in here (and in the for() parentheses)
};
//tuce is *not* visible out here
};
function byE40() {
//nish *is* visible out here
for( var nish = 0; nish < 5; nish++ ) {
//nish is visible to the whole function
};
//nish *is* visible out here
};
推荐答案
让
是在Ecma Script 6中引入的 - 新的javascript版本 - 在撰写本文时仍处于开发阶段。因此,使用 var
可以让您暂时浏览更多浏览器。
let
is introduced in Ecma Script 6 - the new javascript version - which is still in development at the time of this writing. Therefore, using var
will get you across more browsers for the time being.
另一方面,我敦促人们使用让
代替 var
从现在开始。我会继续列出原因,但你已经在帖子中有一个链接,其中有一个很好的解释。简而言之,让
帮助您避免javascript中的变量提升,并将变量的范围保持在需要的位置。
On the other hand, I urge people to use let
instead of var
from now on. I would go ahead and list the reasons but you have already have a link in your post with a great explanation in it. Long story short, let
helps you avoid the variable hoisting in javascript and keep your variables' scope at just where it needs to be.
在我最近获得一个upvote之前,我已经忘记了这篇文章。我想更新这个声明。我个人现在尽可能多地使用 const
。如果您开始使用我强烈推荐的代码,并使用类似airbnb lint规则的东西,它也会告诉您使用const。它会使您的变量保持不变,因此一旦设置了它们就不能改变它们,因此它并不适用于所有情况。 const
和让
在范围方面也优于 var
非常值得一读。我的使用等级是这样的 const
> 让
> var
I've forgotten about this post until I recently got an upvote. I'd like to update this statement. I personally use const
as much as I can these days. If you get into linting your code, which I highly recommend, and use something like airbnb lint rules, it will also tell you to use const. It will make your variables a constant so you will not be able to mutate them once you set their value thus it is not applicable in all cases. const
and let
also have advantages in terms of scope over var
and it is well worth a read. My hierarchy of usage goes as such const
> let
> var
这篇关于在javascript for循环中'let'vs'var',是否意味着使用'var i = 0'的所有for循环实际上应该是'let i = 0'而是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!