0

numberHands will be equal to 1,2, or 3. It will never make it this far in the program if not. So I see no reason for else statements.

But, is this the correct syntax for writing nested if statements in JavaScript? I feel like the closing brackets are incorrect, but I'm new to js. How would you write this?

function recap() {
    if (numberHands > 0) {
        wonOrLost(h1.cards, h1);
    }
        if (numberHands > 1) {
            wonOrLost(h2.cards, h2);
        }
            if (numberHands > 2) {
                wonOrLost(h3.cards, h3);
            }
    playAgainOption();
}
4

5 回答 5

2

Give this a try...

function recap() {
    switch(numberHands) {
        case 3:
            wonOrLost(h3.cards, h3);
        case 2:
            wonOrLost(h2.cards, h2);
        case 1:
            wonOrLost(h1.cards, h1);
    }
    playAgainOption();
}

It looks like the order these functions execute doesn't matter as long as they all get called. To me, this solutions feels more elegant.

Good luck!

于 2013-12-24T16:42:38.513 回答
2

你是对的,右括号在错误的位置。你正在寻找的是

function recap() {
    if (numberHands > 0) {
        wonOrLost(h1.cards, h1);
        if (numberHands > 1) {
            wonOrLost(h2.cards, h2);
            if (numberHands > 2) {
                wonOrLost(h3.cards, h3);
            }
        }
    }
    playAgainOption();
}

笔记

这在功能上与您当前拥有的相同。

于 2013-12-24T16:38:33.243 回答
1

好吧,它不是嵌套的,但它仍然会以相同的方式工作。那是因为

  • 如果numberHands > 1那么它也是根据定义> 0
  • 如果numberHands > 2那么它的定义> 1也是> 0如此。

嵌套 if 语句的正确语法是

if (condition) {
    doSomething();
    if (anotherCondition) {
        doSomethingElse();
        if (aThirdCondition) {
            doSomethingDifferent();
        }
    }
}

在您的情况下,您有几个单独的 if 语句,它们彼此不相关,除了如果一个是真的,那么它后面的所有其他语句也是真的。


如果您不打算让它们全部运行 if numberHandsis equal to 3 ,那么switch/case结构更合适,更具可读性: OP 澄清说他确实打算让它们全部运行。

switch (numberHands) {
    case 1:
        wonOrLost(h1.cards, h1);
        break;
    case 2:
        wonOrLost(h2.cards, h2);
        break;
    case 3:
        wonOrLost(h3.cards, h3);
        break;
}
于 2013-12-24T16:40:56.797 回答
1

这不是嵌套if语句,但如果您计划添加更多条件,它肯定是一种替代方法。

var list = [h1,h2,h3];
for (var i = 0; i < numberHands; i++) {
    wonOrLost(list[i].cards, list[i]);
}
于 2013-12-24T17:44:56.010 回答
0

我不知道你是不是不习惯用markdown编辑器写,但那是不正确的缩进。

function recap() {
    if (numberHands > 0) { // 1 or more
        wonOrLost(h1.cards, h1);
        if (numberHands > 1) {
            wonOrLost(h2.cards, h2); // 2 or more
        }
        if (numberHands > 2) {
            wonOrLost(h3.cards, h3); // 3 or more
        }
    }
    playAgainOption();
}
于 2013-12-24T16:45:40.237 回答