0

numberHandsに等しくなり1,2, or 3ます。そうでない場合、プログラムでここまで到達することはありません。したがって、else ステートメントを使用する理由はありません。

しかし、これは JavaScript でネストされた if ステートメントを記述するための正しい構文ですか? 閉じ括弧が間違っているように感じますが、js は初めてです。これをどのように書きますか?

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

おっしゃる通り、閉じ括弧が間違った場所にあります。あなたが探しているのは

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 に答える
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 に答える
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 に答える
1

ネストされていませんが、同じように機能します。その理由は

  • もしそうならnumberHands > 1、それも定義によるもの> 0です。
  • もしそうならnumberHands > 2、それは定義によるもの> 1です> 0

ネストされた if ステートメントの適切な構文は次のようになります。

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

あなたの場合、互いに関連していないいくつかの個別の if ステートメントがありますが、1 つが true の場合、その背後にある他のすべても true であるという事実は別として。


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 に答える
0

マークダウン エディターでの記述に慣れていないかどうかはわかりませんが、インデントが正しくありません。

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 に答える