等效于JavaScript中的continue语句

时间:2016-09-17 08:26:42

标签: javascript

我想知道在JavaScript中,continue语句的结构等价物是什么?我试图摆脱继续声明,但不知道如何。谁能指出我正确的方向?谢谢!

function Hand() {
    this.cards = new Array();

    this.addOneCard = function(card) {
        this.cards.push(card);
    }

    this.evaluateHand = function(){
        // Needs to handle two aces better
        var total1 = new Number;
        var total2 = new Number;

        for(var i in this.cards) {
            if (this.cards[i].value == "A") { 
                total1 += 1;
                total2 += 11;
                continue;
            }
            if (isNaN(this.cards[i].value * 1)) {
                total1 += 10;
                total2 += 10;
                continue;
            } 
            total1 += Number(this.cards[i].value);
            total2 += Number(this.cards[i].value);
        }
        return [total1, total2];
    };
}

4 个答案:

答案 0 :(得分:2)

continue声明在JavaScript中有效。您可以像使用任何语言一样使用它。

在说完之后,你可以阅读这个interesting discussion,了解你为什么要避免它,以及如何避免它。

答案 1 :(得分:1)

else if对会帮助你:

    for(var i in this.cards) {
        if (this.cards[i].value == "A") { 
            total1 += 1;
            total2 += 11;
        }
        else if (isNaN(this.cards[i].value * 1)) {
            total1 += 10;
            total2 += 10;
        } 
        else { 
            total1 += Number(this.cards[i].value);
            total2 += Number(this.cards[i].value);
        }
    }

答案 2 :(得分:0)

这适用于任何语言,而不仅仅是java脚本

function Hand() {
    this.cards = new Array();

    this.addOneCard = function(card) {
        this.cards.push(card);
    }

    this.evaluateHand = function(){
        // Needs to handle two aces better
        var total1 = new Number;
        var total2 = new Number;

        for(var i in this.cards) {
            if (this.cards[i].value == "A") { 
                total1 += 1;
                total2 += 11;
            }
            else if (isNaN(this.cards[i].value * 1)) {
                total1 += 10;
                total2 += 10;
            }
            else {
                total1 += Number(this.cards[i].value);
                total2 += Number(this.cards[i].value);
            }
        }
        return [total1, total2];
    };
}

答案 3 :(得分:-2)

一个选项是:

this.cards.forEach(function(card) {
    if (card.value == "A") { 
        total1 += 1;
        total2 += 11;
        return;
    }
    if (isNaN(card.value * 1)) {
        total1 += 10;
        total2 += 10;
        return;
    } 
    total1 += Number(card.value);
    total2 += Number(card.value);
});

显然有些人认为return会终止所有内容...... return会停止为当前元素运行的函数,使下一次迭代立即开始,就像continue一样。我并不是说这是一个比使用continue更好的选择,但它绝对是另一种选择。