【问题标题】:Am I wrong or new ES doesn't use (as must) "{ }" on if-else statements? [closed]我错了还是新 ES 没有在 if-else 语句上使用(必须)“{ }”? [关闭]
【发布时间】:2022-06-11 16:35:22
【问题描述】:

在 JS 中,我是否需要在 if 和 else 语句之后使用 { } 括号,因为 JS 中给出的两个代码都可以正常工作,提供我所要求的结果?

const MMark = 78;
const MJohn = 95;
const heightMark = 1.76;
const heightJohn = 1.95;
bmiMark = (MMark / heightMark ** 2);
bmiJohn = (MJohn / heightMark ** 2);
markHigherBMI = true;
if (bmiJohn > bmiMark)
    console.log("The BMI of John which is " + bmiJohn + " is greater than Mark's which is: " + bmiMark);
else
    (bmiJohn < bmiMark)
console.log("The BMI of Mark which is " + bmiMark + " is less than John's which is: " + bmiJohn);
if (bmiJohn > bmiMark)
    console.log("The higher BMI is Mark's : " + markHigherBMI);

也适用于大括号:

birthYear = 1990;

if (birthYear >= 2000) {
    let century = 21
} else {
    if (birthYear <= 2000) {
        century = 20
        console.log(`My birth century is ${century} .`);
    }
}

我应该依靠 现在 还是将来 - 使用或不使用大括号?

【问题讨论】:

  • 这不是错误,复合语句从来都不是强制性的。
  • 如果没有{},那么只有第一个语句被视为if-branch body
  • ES,就像大多数从 C 语法衍生而来的语言一样,不需要(也从未需要)围绕单个语句进行卷曲(Perl 是一个例外),但它被认为是一种糟糕的代码风格,因为它可以在以后的编辑中引入细微的错误。因此,诸如 ESLint 之类的 linting 工具通常会配置为将其作为代码异味发出警告。
  • "工作得很好" 当然,除了错误:else (bmiJohn &lt; bmiMark) 根本没有做任何事情。如果它是用来做事的,那就是一个更大的错误。
  • 如果这是documented somewhere...

标签: javascript curly-braces


猜你喜欢
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多