Javascript:||而不是IF声明 - 这是合法的和跨浏览器有效吗? [英] Javascript: || instead of IF statement - is this legal and cross browser valid?
问题描述
似乎:
if (typeof a == 'undefined') {
a = 0;
}
和
(typeof a != 'undefined') || (a = 0)
在Javascript中具有相同的效果。
has the same effect in Javascript.
我真的很喜欢第二个,因为它很短,一行代码,但这是合法的,跨浏览器有效吗?
我的意思是,jslint说它有错误。我应该毫无顾虑地使用它吗?
I really like the second one because it is short, one line code, but is this legal, and cross browser valid? I mean, jslint says it has errors. Should I use it without concerns?
推荐答案
恕我直言 || (a = 0)
与 ||太相似了(a == 0)
因而令人困惑。有一天过分热心的开发人员只会修复它,改变代码的含义。每个其他开发人员都必须坐一会儿才能弄清楚这是你的意图还是一个简单的bug。
IMHO || (a = 0)
is way too similar to || (a == 0)
and thus confusing. One day overzealous developer will just "fix it", changing the meaning of your code. And every other developer will have to sit for a while to figure out whether this was your intent or just a simple bug.
这实际上是 JSLint 试图说的:
预期条件表达式而不是看到作业。
Expected a conditional expression and instead saw an assignment.
我避免使用令人困惑的结构,因为它们会损害可读性。 a = a || 0;
更具识别性和意义相似。
I avoid using confusing constructs as they hurt readability. a = a || 0;
is way more recognizable and similar in meaning.
这篇关于Javascript:||而不是IF声明 - 这是合法的和跨浏览器有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!