我为什么要在string ==""上使用string.length == 0在ECMAScript中检查空字符串时? [英] Why should I use string.length == 0 over string == "" when checking for empty string in ECMAScript?

查看:77
本文介绍了我为什么要在string ==""上使用string.length == 0在ECMAScript中检查空字符串时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前项目中的大多数开发人员使用(对我来说)奇怪的方法来检查ECMAScript中的空字符串:

Most of the developers on my current project use a (to me) strange way to check for empty strings in ECMAScript:

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

我会通常写这个:

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

后一版对我来说似乎更具可读性和自然性。

The latter version seems more readable and natural to me.

我提出的任何人似乎都无法解释版本1的优点。我想在过去的某个时候有人告诉大家这是做这件事的方法,但是现在那个人离开了,没有人记得为什么要这样做这样。

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.

我想知道为什么我应该在第二个版本中选择第一个版本?重要的是,一个版本比另一个版本更好吗?由于某种原因,一个版本更安全还是更快?

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?

(我们实际上是在符合ECMAScript Edition 4的Siebel eScript中执行此操作)

(We actually do this in Siebel eScript which is compliant with ECMAScript Edition 4)

谢谢。

推荐答案

我实际上更喜欢多种语言的技术,因为它有时难以区分在空字符串文字和其他几个字符串之间('' )。

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 (" ", '"').

但在ECMAScript中还有另一个避免 theString ==的原因: 0 ==评估为 true false == 0.0 == ...

But there's another reason to avoid theString == "" in ECMAScript: 0 == "" evaluates to true, as does false == "" and 0.0 == ""...

...所以除非你知道 theString 实际上是一个字符串,你最终可能会因为弱比较而给自己造成问题。幸运的是,你可以通过明智地使用严格相等( === )运算符来避免这种情况:

...so unless you know that theString is actually a string, you might end up causing problems for yourself by using the weak comparison. Fortunately, you can avoid this with judicious use of the strict equal (===) operator:

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



参见:



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