-1

我是学习 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;
}
4

3 回答 3

2

对于 a 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');
    }
}
于 2013-04-02T02:29:08.607 回答
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;
}
于 2013-04-02T02:32:24.327 回答
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
于 2013-04-02T02:31:27.567 回答