我当前项目中的大多数开发人员都使用一种(对我来说)奇怪的方式来检查 ECMAScript 中的空字符串:
if (theString.length == 0)
// string is empty
我通常会这样写:
if (theString == "")
// string is empty
后一个版本对我来说似乎更具可读性和自然性。
我问过的人似乎都无法解释版本 1 的优点。我想过去某个时候有人告诉每个人这是这样做的方法,但现在那个人离开了,没有人记得为什么应该这样做方式。
我想知道我是否有理由选择第一个版本而不是第二个版本?一个版本比另一个版本好吗?这很重要吗?由于某种原因,某个版本是否更安全或更快速?
(我们实际上是在 Siebel eScript 中执行此操作,它符合 ECMAScript Edition 4)
谢谢。
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
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.
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)
Thanks.
发布评论
评论(3)
实际上,我更喜欢多种语言中的这种技术,因为有时很难区分空字符串文字
""
和其他几个字符串 (" "
,' "'
)。但是在 ECMAScript 中还有一个避免使用
theString == ""
的原因:0 == ""
计算结果为true
,就像false == ""
和0.0 == ""
......所以除非您知道
theString
实际上是一个字符串,使用弱比较可能最终会给自己带来问题,幸运的是,您可以通过明智地使用严格等于 (==) 来避免这种情况。 =
) 运算符:另请参阅:
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 totrue
, as doesfalse == ""
and0.0 == ""
......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:See also:
问题是,如果将
theString
设置为0
(零),您的第二个示例将评估为 true。The problem is that if
theString
is set to0
(zero) your 2nd example will evaluate to true.正确答案是正确的,理解类型检查很重要。但就性能而言,字符串比较每次都会输给 .length 方法,但幅度非常非常小。如果您对降低网站速度几毫秒不感兴趣,您可能需要选择对您以及更重要的是对您的团队更具可读性/可维护性的内容。
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. 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.