开发者

Break out of function within enumarable.each iteration

I have a Prototype class - within the class i call a function and within this function i do en enumerable.each iteration. If an element within this iteration fails a check i then call another function which then re-calls this same function later. Can i break within this iteration so not only the iteration is ended but nothing else within the function is called.

Say with this code i wouldnt want the console.log to be called if elm.something == 'whatever'. Obviously i could set a variable and then check fo开发者_Python百科r this after the function but is there something else that i should be doing?

myFunction: function(el){
    el.each(function(elm){ 
        if(elm.something == 'whatever'){
            this.someOtherFunction(elm);
        }
    },this);            
    console.log("i dont want this called if elm.something == 'whatever'");
}

Just to be clear, in this case the console.log is just placeholder code for the beginnings of some additional logic that would get executed after this loop


You answered it yourself "Obviously i could set a variable and then check for this after the function"

In this case, you're basically looking to not call the console.log even if elm.something == 'whatever' for a single 'elm'

myFunction: function(el){
    var logIt = true;
    el.each(function(elm){ 
        if(elm.something == 'whatever'){
            logIt = false;
            this.someOtherFunction(elm);
        }
    },this);            
    logIt && console.log("i dont want this called if elm.something == 'whatever'");
}


The simplest way would be to avoid using each() and instead rewrite using a for loop:

myFunction: function(el){
    for(var i in el) {
      var elm = el[i];
        if(elm.something == 'whatever'){
            return this.someOtherFunction(elm);
        }
    }
    console.log("i dont want this called if elm.something == 'whatever'");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜