-1

如何在 For 循环的末尾添加条件?

例子:

if (state) {
    for (var i = 0, l = $imageLength; i < l; i++) {
        if ($images[i].url === state) {
            rGallery.init(i);
            break;
        }
    }

    /* Need to add here: if NOT in loop... blah*/

} else {
    rGallery.init();
}

旁注,也可以改进逻辑以避免它... if (state has a match in the loop) init(i) else init()

4

3 回答 3

2

使用布尔变量怎么样:

var hasMatch = false;
if (state){
    for (var i = 0, l = $imageLength; i < l; i++){
        if ($images[i].url === state){
            rGallery.init(i);
            hasMatch = true;
            break;
        }
    }
}
if(!hasMatch){
    rGallery.init();
}
于 2012-12-20T07:56:29.960 回答
1

您可以使用另一个变量作为标志并在循环后检查它:

var found = false;
if (state){
    for (var i = 0, l = $imageLength; i < l; i++){
        if ($images[i].url === state){
            rGallery.init(i);
            found = true;
            break;
        }
    }
}

if (!found){
    rGallery.init();
}
于 2012-12-20T07:56:28.870 回答
1

如果在循环中找到结果,您可以设置一个标志:

var found = false;
for (var i = 0, l = $imageLength; i < l; i++){

    if ($images[i].url === state){

        rGallery.init(i);
        fount = true;
        break;
    }
}
if (!found) {
    /* Need to add here: if NOT in loop... blah*/
}
于 2012-12-20T07:56:50.520 回答