JavaScript 单行“if"语句 - 最佳语法,此替代方案? [英] JavaScript single line 'if' statement - best syntax, this alternative?

查看:35
本文介绍了JavaScript 单行“if"语句 - 最佳语法,此替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们已经清楚地表明,尽管意见仍然存在,在单行 if 语句中放弃大括号对于可维护性和可读性来说并不理想.

It's been clearly put, although opinion none the less, that forgoing curly brackets on a single line if statement is not ideal for maintainability and readability.

但是这个呢?

if (lemons) { document.write("foo gave me a bar"); }

压缩的更厉害,如果展开,大括号也不会忘记.有没有明显的问题,如果没有,有什么考虑?我觉得它仍然非常易读,至少和三元运算符一样好.在我看来,由于可读性,三元运算符的建议并不多,尽管我觉得这个结论并不完全一致.

It's even more compressed, and if expanded, the curly brackets won't be forgotten. Are there any blatant problems, and if not, what are the considerations? I feel like it's still very readable, at least as much as a ternary operator anyway. It seems to me like ternary operators aren't suggested as much due to readability, although I feel like that that conclusion isn't quite as unanimous.

我心中的邪恶双胞胎想提出这个建议,尽管语法显然不是为了它,而且可能只是一个坏主意.

The evil twin in me wants to suggest this, although the syntax obviously isn't meant for it, and is probably just a bad idea.

(syntax) ? document.write("My evil twin emerges"): "";

推荐答案

我已经看到了用于实现此目的的 && 操作符的短路行为,尽管人们没有习惯了这个可能会觉得难以阅读,甚至称其为反模式:

I've seen the short-circuiting behaviour of the && operator used to achieve this, although people who are not accustomed to this may find it hard to read or even call it an anti-pattern:

lemons && document.write("foo gave me a bar");  

就个人而言,我会经常使用不带括号的单行 if,如下所示:

Personally, I'll often use single-line if without brackets, like this:

if (lemons) document.write("foo gave me a bar");

如果我需要添加更多语句,我会将语句放在下一行并添加括号.由于我的 IDE 会自动缩进,因此对这种做法的可维护性反对没有实际意义.

If I need to add more statements in, I'll put the statements on the next line and add brackets. Since my IDE does automatic indentation, the maintainability objections to this practice are moot.

这篇关于JavaScript 单行“if"语句 - 最佳语法,此替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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