有没有办法避免在这个 JavaScript 块中进行 eval ?

发布于 2024-10-11 02:17:58 字数 287 浏览 1 评论 0原文

有没有办法避免在这段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');
 }
} ());

Is there a way to avoid eval in this block of js?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泛滥成性 2024-10-18 02:17:58

这里的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');
       }
   }
} ());

The eval here is completely pointless:

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

This will do the exact same thing, also note that r leaks into the global scope.

// 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');
       }
   }
} ());
撧情箌佬 2024-10-18 02:17:58

怎么样

if (typeof window[r] == "undefined")

How about

if (typeof window[r] == "undefined")
°如果伤别离去 2024-10-18 02:17:58
 while (r = requires.pop()) {
  if (typeof window[r] == "undefined") alert(r + ' is required');
 }
 while (r = requires.pop()) {
  if (typeof window[r] == "undefined") alert(r + ' is required');
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文