I would like to specify the while's condition as a variable, something like:
function doWhile(condition){
while(condition){
number++;
}
alert(number);
}
var number = 1;
doWhile(number < 10);
asked May 15, 2011 at 14:25
Adam Halasz
58.5k67 gold badges154 silver badges216 bronze badges
1 Answer 1
The only way to do this is using functions.
function doWhile(condition, action, undefined) {
var current = undefined;
// call your condition with the current value
while(condition(current)) {
// do something with the current value then update it
current = action(current);
}
return result;
}
var number = doWhile(function condition(number) {
// if the current value has no value yet continue
// if the current value is less than 10
return number === undefined || number < 10;
}, function action(number) {
// if the number has no value set it to 0
if (number === undefined) {
number = 0;
}
// increase it
return ++number;
});
console.log(number);
answered May 15, 2011 at 14:30
Raynos
170k57 gold badges359 silver badges399 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
user113716
What, you don't want to run
eval() in a loop? ;o) +1Raynos
@patrick_dw I was tempted. But I decided to do it properly. Besides if I show him the eval solution, he'll go "thats easier/nicer I'll just use that. What do you mean eval is bad? eval is fine!"
user113716
@Raynos: I saw that exact situation earlier this year, but with someone giving a solution using
with. It took only a few minutes for OP to break his code, but was convinced that with was the solution anyway.Adam Halasz
Well, it works, but I don't really understand what's going on :S,
return number === undefined || number < 10; Why do I need the number === undefined part from here?Raynos
@CIRK the first call is
undefined. You can initialize result = 0 if you want. But then it defaults to 0 instead of undefined and wouldn't work nicely with strings or arrays. I can imagine this looking alien if your not used to passing first class functions around like this. |
Explore related questions
See similar questions with these tags.
lang-js