简体   繁体   English

javascript循环中断

[英]javascript break of of loop

I know i should know how to do this but some how it escapes me. 我知道我应该知道该怎么做,但是有一些它如何使我逃脱。 I need to exit the loop here once I have a match. 比赛结束后,我需要在这里退出循环。 Why does this not work? 为什么这不起作用?

ubot.registry.queue.each(function (dj, idx) {
    console.log(idx);
    var user = ubot.registry.users.get(dj.userid);
    console.log(user.name);
    console.log(rm_user)
    if(user.name == rm_user) {
        console.log(dj.userid);
        return; // not exiting loop here 
        /*
        if(!ubot.dj_timeout) {
            ubot.remUserFromQueue(user);
            return true;
        } else {
            console.log(ubot.dj_timout);
        }
        */
    }
});

Here's a generic solution since you haven't given us specifics on the code you're running. 这是一个通用的解决方案,因为您没有向我们提供有关正在运行的代码的详细信息。

It doesn't break the loop. 它不会打破循环。 Instead it prevents the code inside the function from running once a flag is set. 相反,一旦设置了标志,它将阻止函数内的代码运行。

var flag = false;

ubot.registry.queue.each(function (dj, idx) {
    if( !flag )
        var user = ubot.registry.users.get(dj.userid);
        if(user.name == rm_user) {
            console.log(dj.userid);
            flag = true;
            // rest of the code
        }
    }
});

"Why does this not work?" “为什么这不起作用?”

You're returning undefined , but functions always return undefined unless a specific return value is provided. 您将返回undefined ,但是函数始终返回undefined除非提供了特定的返回值。 So by doing return; 因此,通过return; you're not doing anything different than the function would do anyway. 您所做的任何事情都不会与该函数所做的事情有所不同。

You don't say what framework you're using, but I'm going to take a wild guess and suppose that you're using Prototype's Enumerable.each . 您没有说您正在使用什么框架,但是我将做出一个疯狂的猜测,并假设您正在使用Prototype的Enumerable.each If so, you can exit the "loop" by using this statement: 如果是这样,您可以使用以下语句退出“循环”:

throw $break;

which throws a custom exception that the each method understands as meaning "break out of the 'loop'". 引发一个自定义异常, each方法都将其理解为“突破'循环'”的含义。

如果您可以访问each() ,那么也许您就可以访问some()any()之类的东西-即each()的可短路版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM