让var或var让 [英] let var or var to let

查看:115
本文介绍了让var或var让的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几个月里,我一直在学习很多关于JavaScript的知识。多年来一直滥用这些语言,我敢说我现在对语言有了更好的理解,并且我已经爱> 其功能性的好处。

最近我接受了学习计划,但这只是为了好玩。浏览 MDN参考我注意到JS虽然缺少块范围,但确实有一个关键字,可用于声明给定块的本地变量,非常类似于Scheme的 let

In the last couple of months, I've been learning a lot about 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:

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

鉴于:

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

那么什么我现在想知道的是:为什么更频繁地使用?它与X浏览器支持有关吗?它只是其中一个鲜为人知的好东西吗?简而言之,使用 var 超过<$ c的优点是什么? $ c>让,有什么警告?

So what I want to know now is: Why isn't let used more often? Has it got something to do with X-browser support? Is it just one of those lesser-known-goodies?
In short, what are the advantages of using var over let, what are the caveats?

据我所知,的行为让,如果有的话,更一致(单个块中的双重声明引发 TypeError ,但函数体除外(ECMA6草稿修复此问题)。

老实说,除了这个功能/关键字不是很出名之外,我很难想到任何参数反对使用 for循环,或临时变量使代码更易读的任何地方。

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).
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.

推荐答案

是的,它完全是为了使用浏览器支持。目前只有Firefox实现它(因为它是ECMAScript超集的一部分)

Yes, it has entirely to do with browser support. Currently only Firefox implements it (since it's part of their superset of ECMAScript).

但它是在ES6中发布,所以有希望......

But it is coming in ES6, so there's hope...

我怀疑我可以说, var 有很多好处,因为两者都受支持。我认为口头禅将是是新的 var

I doubt it could be said that there are many benefits to var over let given that both are supported. I think the mantra is going to be "let is the new var"

这篇关于让var或var让的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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