【问题标题】:Curly brackets at the end of the if statement changes how the program behaves (contrary to not adding the brackets at all). Why?if 语句末尾的大括号改变了程序的行为方式(与根本不添加括号相反)。为什么?
【发布时间】:2019-08-03 03:48:41
【问题描述】:

只有在选择100以上的选项时,差异才明显,即使括号内没有任何东西也会发生。

我是 JS 新手,现在已经自学了将近一个星期。想知道为什么这个小改动会产生“不同”的结果。

function To10(numTo10) {
  let rest = 100 - numTo10;
  if (numTo10 < 100) {}
  document.write("How much to 100? ");
  return rest;
}
document.write(To10(1))

任何大于 99 的数字(例如 100)使用括号打印: 多少到100? -1

如果没有括号,任何高于 99(同样是 100)的数字都会打印: -1

【问题讨论】:

    标签: javascript brackets


    【解决方案1】:

    因为没有大括号,所以解释为:

    if (numTo10 < 100) document.write("How much to 100? ");
    

    相当于:

    if (numTo10 < 100) {
      document.write("How much to 100? ");
    }
    

    在这种情况下,反转条件更容易且更少混乱:

    if (numTo10 >= 100) {
      document.write("How much to 100 ?");
    }
    

    【讨论】:

    • 我认为他不想打印“How much to 100?”如果数字是 100 或更高。
    【解决方案2】:

    {}被认为是块语句,用于将多条语句合二为一,

    所以当你在 if 语句之后不使用 {} 时,如果条件评估为真,它会执行下一条语句

    if(true)
    console.log('true hello')
    
    if(false)
    console.log('false hello')

    如果你使用{},而不是如果 if 评估为 true,它会尝试在 {} 内运行代码,在这种情况下它是空块,所以它什么都不做

    if (true){}
      console.log('true hello')
    
    if (false){}
      console.log('false hello')

    为了避免这种混淆,如果条件语句为真,最好在{} 中添加要运行的代码

    【讨论】:

      猜你喜欢
      • 2020-08-22
      • 1970-01-01
      • 2011-04-11
      • 2020-09-17
      • 2022-01-20
      • 2017-01-27
      • 2012-12-16
      • 2019-04-18
      相关资源
      最近更新 更多