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

查看:1335
本文介绍了JavaScript单行'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");  

就个人而言,如果 $ c>没有括号,如下所示:

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天全站免登陆