【问题标题】:When I do not use curly braces in a javascript function, does it matter? [duplicate]当我不在 javascript 函数中使用花括号时,这有关系吗? [复制]
【发布时间】:2017-05-24 16:20:50
【问题描述】:

比如我写这种代码的时候;

var power = function(base, exponent) {
            var result = 1;
            for(var count = 0; count<exponent; count++) 
            result *= base;
            return result;

            };
        console.log(power(2, 10));

我得到 1024,但是当我写这种代码时;

var power = function(base, exponent) {
            var result = 1;
            for(var count = 0; count<exponent; count++) {
            result *= base;
            return result;
            }   
            };
        console.log(power(2, 10));

我得到2,我很困惑,这种情况下大括号的逻辑是什么。

【问题讨论】:

  • 通过使用大括号,您将return 放入for,因此它只会执行一次。
  • 谢谢,我明白了,但是return语句总是让我很困惑。

标签: javascript curly-braces


【解决方案1】:
for(var count = 0; count<exponent; count++) 
result *= base;

等价于

for(var count = 0; count<exponent; count++) {
    result *= base;
}

第一个块完全运行,因为默认情况下 for 循环只包括它后面的行,所以“return”直到循环完全执行后才会被命中。

在第二个代码块中,您的循环只执行一次,因为函数一按“return”就退出。

【讨论】:

    【解决方案2】:

    当块内只有一个语句时,您可以省略控制块中的花括号。虽然允许,但不建议这样做,因为它是一种常见的编码模式,会导致错误。

    查看这些示例:

    // Not using the braces leads to confusing code that can cause bugs:
    
    if("scott" === "scott")
      console.log("scott === scott");
      console.log("Am I from the true section of the if/then or not?");
      
    // Using them makes it much more simple to understand the code
    if("scott" === "scott"){
      console.log("scott === scott");
    }
    console.log("I am clearly not from the true section of the if/then!");

    【讨论】:

      【解决方案3】:

      始终使用花括号,不使用它们会导致意外行为。问题是,您需要在 for 循环之外返回:

      var power = function(base, exponent) {
                    var result = 1;
                    for(var count = 0; count<exponent; count++) {
                      result *= base;
                    }  
                    return result;
                  };
              console.log(power(2, 10));
      

      【讨论】:

        猜你喜欢
        • 2018-07-24
        • 2020-11-13
        • 1970-01-01
        • 2014-04-23
        • 2019-11-13
        • 2013-08-10
        • 1970-01-01
        • 2020-06-21
        相关资源
        最近更新 更多