Javascript:作为While条件的变量
我想将while的条件指定为变量,类似于:Javascript:作为While条件的变量,javascript,variables,while-loop,conditional-statements,Javascript,Variables,While Loop,Conditional Statements,我想将while的条件指定为变量,类似于: function doWhile(condition){ while(condition){ number++; } alert(number); } var number = 1; doWhile(number < 10); 功能关闭(条件){ while(条件){ 数字++; } 警报(编号); } var数=1; 道希尔(人数
function doWhile(condition){
while(condition){
number++;
}
alert(number);
}
var number = 1;
doWhile(number < 10);
功能关闭(条件){
while(条件){
数字++;
}
警报(编号);
}
var数=1;
道希尔(人数<10人);
实现这一点的唯一方法是使用函数
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);
函数待命(条件、动作、未定义){
无功电流=未定义;
//使用当前值调用您的条件
while(条件(当前)){
//使用当前值执行某些操作,然后更新它
电流=动作(电流);
}
返回结果;
}
var编号=doWhile(功能条件(编号){
//如果当前值没有值,则继续
//如果当前值小于10
返回编号===未定义| |编号<10;
},功能动作(编号){
//如果数字没有值,则将其设置为0
如果(数字===未定义){
数字=0;
}
//增加它
返回++数字;
});
控制台日志(编号);
什么,你不想在循环中运行eval();o)+1@patrick_dw我被诱惑了。但我决定把它做好。此外,如果我向他展示eval解决方案,他会说:“那更简单/更好,我就用它。你说eval不好是什么意思?eval很好!”@Raynos:今年早些时候我看到了确切的情况,但有人用with
给出了解决方案。OP只花了几分钟就破解了他的代码,但他确信不管怎样,with
是解决方案。好吧,它是可行的,但我真的不明白发生了什么:s,returnnumber===undefined | | number<10
为什么我需要这里的number===undefined
部分?@CIRK第一个调用是undefined
。如果需要,可以初始化result=0
。但是它默认为0,而不是未定义的
,并且不能很好地处理字符串或数组。如果您不习惯这样传递第一类函数,我可以想象这个看起来像外星人。