循环回迭代

时间:2014-09-25 03:27:00

标签: jquery

我想比较两个值。如果值等于那么循环必须中断并转到下一个迭代。这是我正在使用的代码。

forLoop:
for (var i = 1, len = values.length; i < len; i++) {
    $('.charStyleAddedToDoc .char-style-added h4')
        .each(function(index, element) {
            //check if value matches
            if ($(element)
                .text() == values[i]) {
                // shoud go next for iteration in for loop
                break forLoop;
            }
        });
    html += '<div class="prog-row side-mini-stat clearfix"><div class="char-style-available"><h4>' + values[i] + '</h4></div></div>';
}

我得到的标签未在(break forLoop;)行中定义。

3 个答案:

答案 0 :(得分:1)

尝试类似

的内容
var flag;
for (var i = 1, len = values.length; i < len; i++) {
    //a flag variable to store the state from the each loop
    flag = false;
    $('.charStyleAddedToDoc .char-style-added h4')
        .each(function (index, element) {
        //check if value matches
        if ($(element)
            .text() == values[i]) {
            // shoud go next for iteration in for loop
            //set the flag to true so that we can skip remainder of the for loop
            flag = true;
            //return false to skip further execution of the each loop
            return false;
        }
    });
    //if the flag is set then we can skip the remainder of the loop
    if (flag) {
        continue;
    }
    html += '<div class="prog-row side-mini-stat clearfix"><div class="char-style-available"><h4>' + values[i] + '</h4></div></div>';
}

答案 1 :(得分:0)

尝试使用continue代替break

                        for(var i=1, len = values.length; i<len; i++){
                            $('.charStyleAddedToDoc .char-style-added h4').each(function(index,element){
                                //check if value matches
                                if($(element).text() == values[i]){
                                    // shoud go next for iteration in for loop
                                    continue;
                                }

                            });
                            html+='<div class="prog-row side-mini-stat clearfix"><div class="char-style-available"><h4>'+values[i]+'</h4></div></div>';
                        }

答案 2 :(得分:0)

javascript中label和goto的语法是:

[lbl] <label-name>
goto <label-name>

使用label和goto语句尝试此操作。

[lbl] forLoop:
    for (var i = 1, len = values.length; i < len; i++) {
        $('.charStyleAddedToDoc .char-style-added h4')
            .each(function(index, element) {
                //check if value matches
                if ($(element)
                    .text() == values[i]) {
                    // shoud go next for iteration in for loop
                    goto forLoop;
                }
            });
        html += '<div class="prog-row side-mini-stat clearfix"><div class="char-style-available"><h4>' + values[i] + '</h4></div></div>';
    }