我怎么知道何时使用{}

时间:2013-04-02 02:24:22

标签: javascript curly-brackets

我是学习JavaScript的新手。我开始掌握它,但我正在审查我从一本书中学到的代码行(“Head First”)并且我很难理解何时使用{{1} }

你能帮我理解一下吗?

{}

3 个答案:

答案 0 :(得分:2)

对于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');
    }
}

答案 1 :(得分: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;
}

答案 2 :(得分:0)

使用{}的目的是单独的代码块。

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