【问题标题】:How do I know when to use {} [closed]我怎么知道何时使用 {} [关闭]
【发布时间】:2013-04-02 02:24:21
【问题描述】:

我是学习 JavaScript 的新手。我开始掌握它的窍门,但我正在审查我从一本我正在学习的书(“Head First”)中获得的代码行,我有点难以理解何时使用{}

你能帮我理解吗?

function touchrock() {
    if (userName) {
        alert("I am glad that you have returned " + userName + "! Let's continue searching for your dream car");
    } else {
        userName = prompt("What is your name?");
        if (userName) {
            alert("It is good to meet you, " + userName + ".").onblur = setCookie;
            if (navigator.cookieEnabled);
            else alert("Sorry. Cookies aren't supported");
        }
    }
    document.getElementById("lambo").src = "lamboandgirl.jpg";
    document.getElementByID("lambo").onblur = setCookie;
}

【问题讨论】:

标签: javascript curly-brackets


【解决方案1】:

对于function,您始终需要使用它:

function () {
    // ...
}

对于if 语句或else 语句,它是可选的,但是如果不使用大括号,则它只能执行一行

if (cond)
    // single line...
else
    // single line...

if (cond) {
    // multi ...
    // line ...
} else {
    // multi ...
    // line ...
}

你甚至可以和if/else混搭

if (cond)
{
    // multi ...
    // line ...
}
else
    // single line...

还尝试使用在行尾开始大括号{ 并在下一行开头结束大括号} 的标准。这是编写 JavaScript 的常用标准方式。

function test(cond) {
    if (cond) {
        alert('hello world');
    } else {
        alert('awww');
    }
}

【讨论】:

  • 可选的排序...没有大括号,只有第一行会在条件句内。
  • 虽然花括号对于 if/else 语句是可选的,但我发现出于几个原因使用它们是明智的。它使您的代码更加一致,更易于阅读,并且避免了逻辑错误。
  • @SurrealDreams 这是编程的圣战之一,是否强制使用大括号。
【解决方案2】:

使用 if 这样的语句会令人困惑,应该避免。看起来那里还有一个全局变量。

您可以只为单行块省略括号:

while (condition)
    console.log(2);

// Is the same as

while (condition) {
    console.log(2);
}

但对于多行块,不是

while (condition)
    console.log(2);
    console.log(3);

// Is the same as

while (condition) {
    console.log(2);
}

console.log(3);

只要坚持在任何地方都使用括号。我只在if 语句中(有时)省略它们,其中正文只有一行长并且没有else 块:

if (condition) break;

// Is the same as

if (condition) {
    break;
}

【讨论】:

    【解决方案3】:

    使用 {} 的目的是分隔代码块。

    function touchrock() { // Create a block of code
        if (userName) { // Create another one
            alert("I am glad that you have returned " + userName + "! Let's continue searching for your dream car");
        } else {
            userName = prompt("What is your name?");
            if (userName) {
                alert("It is good to meet you, " + userName + ".").onblur = setCookie;
                if (navigator.cookieEnabled);
                else alert("Sorry. Cookies aren't supported");
            }
        }
        document.getElementById("lambo").src = "lamboandgirl.jpg";
        document.getElementByID("lambo").onblur = setCookie;
    } // End of the first block
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-05
      • 2010-09-10
      • 2012-09-21
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多