javascript - 有没有办法避免在这个 JavaScript block 中进行 eval ?

标签 javascript eval

有没有办法避免在这段js中进行eval?

// Check requirements Prototype and Scriptaculous
(function () {
 var requires = [
  'Prototype'
  , 'Scriptaculous'
 ]
 while (r = requires.pop()) {
  if (eval('typeof ' + r + ' == "undefined"')) alert(r + ' is required');
 }
} ());

最佳答案

这里的eval完全没有意义:

// since everything in the global scope gets defined on 'window'
typeof window[r] === 'undefined'; 

这将做完全相同相同的事情,还要注意r泄漏到全局范围内。

// Check requirements Prototype and Scriptaculous
(function () {
    var requires = ['Prototype', 'Scriptaculous'];

   var r = ''; // make sure to __not__ override a global r
   while (r = requires.pop()) {
       if (typeof window[r] === 'undefined') {
           alert(r + ' is required');
       }
   }
} ());

关于javascript - 有没有办法避免在这个 JavaScript block 中进行 eval ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4628518/

相关文章:

php - 对于每个...休息

javascript - 不使用 eval() 绘制图形

javascript - 这是 eval 邪恶吗?

Python:如何使用字符串索引( '[0][1][0]')作为多维数组的索引

javascript - 带有 ajax 请求的 Bootstrap 模式

javascript - 如何确保扩展类必须在 TypeScript 中设置属性值?

javascript - 如何用钛创建文件?

javascript - Bootstrap 月份选择器无法正常工作

R 计算公式列表中的公式

javascript eval() 方法在过滤时降低了性能