简体   繁体   English

让var或var让

[英]let var or var to let

In the last couple of months, I've been learning a lot about JavaScript. 在过去的几个月里,我一直在学习很多关于JavaScript的知识。 Having abused the languages for years, I dare say that I now have a better understanding of the language and I've come to love the benefits of its functional nature. 多年来一直滥用语言,我敢说我现在对语言有了更好的理解,并且我开始喜欢它的功能性。
Lately I've taken up learning Scheme, but that's just for fun. 最近我接受了学习计划,但这只是为了好玩。 Browsing the MDN reference I noticed that JS, though lacking block scope, does have a keyword that can be used to declare a variable local to a given block, much like Scheme's let : 浏览MDN引用我注意到JS虽然缺少块作用域,但确实有一个关键字可用于声明给定块的本地变量,就像Scheme的let

for (var i=0;i<someArray.length;i++)
{
    console.log(someArray[i]);
}
console.log(i);//will log someArray's length

Whereas: 鉴于:

for (let i=0;i<someArray.length;i++)
{
    console.log(someArray[i]);
}
console.log(i);//undefined

So what I want to know now is: Why isn't let used more often? 所以我现在想知道的是:为什么不能let更多的时候使用? Has it got something to do with X-browser support? 它与X浏览器支持有关吗? Is it just one of those lesser-known-goodies ? 它只是那些鲜为人知的好东西之一吗?
In short, what are the advantages of using var over let , what are the caveats? 简而言之,使用var over let什么好处,有什么警告?

As far as I can tell, the behaviour of let is, if anything, more consistent (double declarations in a single block raise a TypeError , except for function bodies (ECMA6 drafts fix this, though). 据我所知, let的行为,如果有的话,更一致(单个块中的双重声明会引发TypeError ,但函数体除外(ECMA6草稿虽然修复了这个)。
To be honest, apart from this feature/keyword not being very well known, I struggle to think of any argument against using let for loops, or anywhere where a temporary variable makes for more readable code. 说实话,除了这个功能/关键字不是众所周知之外,我很难想到任何反对使用let for循环的参数,或者临时变量使代码更易读的任何地方。

Yes, it has entirely to do with browser support. 是的,它完全与浏览器支持有关。 Currently only Firefox implements it (since it's part of their superset of ECMAScript) . 目前只有Firefox实现它(因为它是ECMAScript超集的一部分)

But it is coming in ES6 , so there's hope... 但它正在ES6中出现 ,所以有希望......

I doubt it could be said that there are many benefits to var over let given that both are supported. 我怀疑这可以说有很多好处varlet给两者都支持。 I think the mantra is going to be " let is the new var " 我认为口头禅是let新的var

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM