如果、for或while的正文为空,请使用空大括号而不是分号

if, for, or while with an empty body, use empty braces instead of a semi-colon

本文关键字:请使用 while 正文 如果 for      更新时间:2023-09-26

使用谷歌闭包编译器,我得到以下警告消息:

WARNING - If this if/for/while really shouldnt have a body, use {}.

文件上写着:

此警告意味着您在if、for或while语句。例如:

// Produces JSC_SUSPICIOUS_SEMICOLON warning:
if (true);
else alert('no');

这只是一个代码约定,还是{}由于某种原因比;更好?

这可以防止以下情况:

if(condition);
{
    // oops, I really meant for this to be conditional.
    // now it always executes, regardless of condition.
}

引发的错误迫使您将空的{}显式地放在;之前,所以很明显这就是您想要的。