javascript - 如何在不使用 eval() 的情况下使用回调更新函数包装的 while 中的条件?

标签 javascript security while-loop eval

我想定义一个充当 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/

相关文章:

macos - 我的 OSX 应用程序应如何存储用户的私钥?

c# - 为什么我的 WPF 应用程序中会出现 System.Security.AccessControl.PrivilegeNotHeldException?

PHP while循环从数据库获取发布数据

python - Python 中的 For 循环与多处理

javascript - 折叠可见时,如何通过点击 body 隐藏我的折叠 Bootstrap 3 导航栏?

php - 如何使用 php 命令使注册表单高度安全?

javascript - 如何使用 require js shim 加载 google map 依赖项?

python - 有什么理由在 Python 中使用 "while 1, do something, break"吗?

javascript - WordPress REST API 自定义表单提交 - React

javascript - 如何显示隐藏元素前元素并显示一个嵌套的 ul