这个 Javascript 代码中的 eval () 是危险的吗?

Is eval () dangerous in this Javascript code?

我在下面的案例中发现了一个关于eval()的危险的类似问题,但是答案没有解决问题并回答了If it was dangerous or not,它只是建议了另一种方法.这就是为什么我再次询问希望得到新答案的原因。也是2016年发的

所以我想传递一个条件作为参数,我知道这可以是一个函数,但我读过 eval ()new function () {return ...;} 快 67%,这就是为什么我正在使用 eval ()

这是代码

var a = [0];


function LoopWithDelay (func, delay, param, condition){

 console.log(eval (condition));
 
  if (eval (condition)) {
  func (param);
  setTimeout (LoopWithDelay, delay, func, delay, param, condition);
 }
}


function increment (x){
 x[0] += 5;
}


LoopWithDelay (increment, 1000, a, "a[0]<10" );

调用 LoopWithDelay() 函数时,我将最终参数(条件)作为字符串传递,以便在函数内部对其进行求值 eval (condition)

在这种情况下使用eval()是错误的吗?

[已编辑]
我的主要重点是使此代码可重用并消除冗余。这就是为什么我想将条件作为参数传递。

示例:
在测试应用程序中,屏幕根据剩余时间以不同速度闪烁。
如果 t = 0s 每 2000ms 闪烁
如果 10s 等等

看起来您真的只是在尝试进行动态测试,该测试可以对运行时代码中发生的某些变化做出反应。您通常会通过将函数作为参数传递来执行此操作,而不是将代码稍后 "eval()ed" 的字符串。这是您通常传递 "behavior" 或评估仅在运行时可用的内容的方式。它在 javascript 中 非常 常见。这具有相同的行为,但不需要 eval():

var a = [0];

function LoopWithDelay(func, delay, param, condition) {

  let condition_val = condition()
  console.log(condition_val);

  if (condition_val) {
    func(param);
    setTimeout(LoopWithDelay, delay, func, delay, param, condition);
  }
}


function increment(x) {
  x[0] += 5;
}

// capture `a` in the closure of the passed-in function
LoopWithDelay(increment, 1000, a, () => a[0] < 10);