我想定义一个充当 while
语句的函数(带有一些插件,但为了简单起见,我将在此处展示一个基本的包装器) 。因此,将条件作为第一个参数,在每个循环中执行的回调作为第二个参数。
我首先使用的是这个版本:
const wrappedWhile = (conditions, callback) => {
let avoidInfinite = 0;
while (conditions) {
callback();
if (avoidInfinite >= 10) {
console.log('breaking while statement for avoiding infinite loop');
break;
}
avoidInfinite++;
}
};
let i = 0;
wrappedWhile(i < 5, () => {
console.log('log from callback: i =', i);
if (i >= 5) {
console.log('the loop continues whereas it should stop');
}
i++;
});
从逻辑上讲,预计当 i >= 5
时停止。但 conditions
参数是 wrappedWhile
函数中的一个简单 bool 值,因此它始终为 true
,因为 i
较小通话时超过 5
。
然后,我想出了另一个版本,其中在循环的每次迭代中都会评估条件
:
const wrappedWhile = (conditions, callback) => {
while (Function('return ' + conditions + ';')()) {
callback();
}
};
let i = 0;
wrappedWhile('i < 5', () => {
console.log('log from callback: i =', i);
i++;
});
但是,如果我没记错的话,Function
正在使用 eval()
来工作,我们所有人都曾经听说过 eval 的用法()
对于代码注入(inject)来说并不真正安全。
现在我的问题很简单:是否有更安全的替代方案来实现我想要实现的目标?
经过一番研究,我发现了一个link它展示了一种在沙箱环境中评估的方法,但我不知道这是否是好方法。
最佳答案
您应该传递一个函数作为条件并在 while 循环中调用它
const wrappedWhile = (conditions, callback) => {
let i = 0;
while (conditions(i)) {
callback(i);
if (i >= 10) {
console.log('breaking while statement for avoiding infinite loop');
break;
}
i++;
}
};
wrappedWhile((i) => (i < 5), (iteration) => {
console.log('log from callback: i =', iteration);
});
关于javascript - 如何在不使用 eval() 的情况下使用回调更新函数包装的 while 中的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55725235/