Javascript:||而不是IF声明 - 这是合法的和跨浏览器有效吗? [英] Javascript: || instead of IF statement - is this legal and cross browser valid?

查看:84
本文介绍了Javascript:||而不是IF声明 - 这是合法的和跨浏览器有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎:

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屋!

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