简体   繁体   English

在ECMAScript中检查空字符串时,为什么要在string ==“”上使用string.length == 0?

[英]Why should I use string.length == 0 over string == “” when checking for empty string in ECMAScript?

Most of the developers on my current project use a (to me) strange way to check for empty strings in ECMAScript: 我当前项目中的大多数开发人员使用(对我而言)奇怪的方法来检查ECMAScript中的空字符串:

if (theString.length == 0)
    // string is empty

I would normally write this instead: 我通常会这样写:

if (theString == "")
    // string is empty

The latter version seems more readable and natural to me. 后一版本对我来说似乎更具可读性和自然性。

Nobody I asked seemed to be able to explain the advantages of version 1. I guess that at some time in the past somebody told everybody that this is the way to do it, but now that person left and nobody remembers why it should be done this way. 我没有问过任何人似乎能够解释版本1的优点。我想在过去的某个时候有人告诉大家这是做到这一点的方法,但现在那个人离开了,没有人记得为什么要这样做方式。

I'm wondering whether there is a reason why I should choose the first version over the second? 我想知道为什么我应该在第二个版本中选择第一个版本? Does it matter, is one version better than the other one? 重要的是,一个版本比另一个版本更好吗? Is one version safer or faster for some reason? 由于某种原因,一个版本更安全还是更快?

(We actually do this in Siebel eScript which is compliant with ECMAScript Edition 4) (我们实际上是在符合ECMAScript Edition 4的Siebel eScript中执行此操作)

Thanks. 谢谢。

I actually prefer that technique in a number of languages, since it's sometimes hard to differentiate between an empty string literal "" and several other strings ( " " , '"' ). 我实际上更喜欢使用多种语言的技术,因为有时很难区分空字符串文字""和其他几个字符串( " "'"' )。

But there's another reason to avoid theString == "" in ECMAScript: 0 == "" evaluates to true , as does false == "" and 0.0 == "" ... 但是还有另一个原因可以避免ECMAScript中的theString == ""0 == ""评估为true ,假如false == ""0.0 == "" ......

...so unless you know that theString is actually a string , you might end up causing problems for yourself by using the weak comparison. ...所以,除非你知道 theString 实际上是一个字符串 ,否则你最终可能会因为弱比较而给自己造成问题。 Fortunately, you can avoid this with judicious use of the strict equal ( === ) operator: 幸运的是,您可以通过明智地使用strict equal( === )运算符来避免这种情况:

if ( theString === "" )
   // string is a string and is empty

See also: 也可以看看:

问题是如果将theString设置为0 (零),则第二个示例将评估为true。

The correct answer is correct and it's important to understand type checking. 正确的答案是正确的,理解类型检查很重要。 But as far as performance, a string compare is going to lose to .length method every time, but by a very very small amount. 但就性能而言,字符串比较每次都会失去.length方法,但只是非常少量。 If you aren't interested in shaving milliseconds from your site speed, you may want to choose what is more readable / maintainable to you and , more importantly, your team. 如果您对网站速度的剃须毫秒不感兴趣,您可能希望选择更易读/可维护的内容,更重要的是您的团队。

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

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