使用eval()定义变量显示未定义的错误

Defining variable using eval() shows undefined error

本文关键字:显示 未定义 错误 变量 定义 eval 使用      更新时间:2023-09-26

当直接定义变量时,它是有效的。与下面的代码一样,在IE中,正文的背景色将是浅绿色,在非IE浏览器中,正文将是浅蓝色。

<html>
<body>
    <script>
        if (window.attachEvent) {
            var YourBrowserIsIE = true;
        }
        if (YourBrowserIsIE) {
            document.body.style.backgroundColor = 'lightgreen';
        }
        else {
            document.body.style.backgroundColor = 'lightblue';
        }
    </script>
</body>
</html>


然而,有时需要使用eval()定义变量,如下所示,但结果会显示一个错误,表明YourBrowserIsIE在非IE浏览器中未定义。

if (window.attachEvent) {
    eval('var YourBrowserIsIE = true;');
}


是的,我知道我可以为非IE浏览器预定义var YourBrowserIsIE = false;,或者将if语句更改为if (typeof YourBrowserIsIE != 'undefined'),但我希望尽可能减少代码。

那么,有没有一种解决方案可以使用eval()定义变量,并使用简单的if (YourBrowserIsIE)检查变量,而不会在非IE浏览器中显示任何错误?


===EDIT===

抱歉说不清楚。上面提到的使用eval()的情况实际上是为了检测IE版本。请参阅以下代码。

<html>
<body>
    <script>
        if (window.attachEvent) {
            var version = /msie ('d+)/i.exec(navigator.userAgent)[1];
            eval('var YourBrowserIsIE' + version + ' = true;');
        }
        if (YourBrowserIsIE9) {
            document.body.style.backgroundColor = 'lightgreen';
        }
        else {
            document.body.style.backgroundColor = 'lightblue';
        }
    </script>
</body>
</html>

但我想把代码保持在尽可能小的

那不是window.YourBrowserIsIE = window.attachEvent;吗?

我看到它的两个优点:

  1. 它是最小的
  2. 它不需要eval

看到你的代码,我建议根本不要使用YourBrowserIsIE,而是使用:

document.body.style.backgroundColor = window.attachEvent 
                                       ? 'lightgreen' : 'lightblue';

看到你的编辑,那可能是:

document.body.style.backgroundColor = 
              +((/msie ('d+)/i.exec(navigator.userAgent)||[0])[1]) === 9 
                ? 'lightgreen' : 'lightblue'; 

如果它必须是一个可重复使用的变量,我会回到解决方案1:

window['YourBrowserIsIE'+((/msie ('d+)/i.exec(navigator.userAgent)||[0])[1]] 
       = true;
document.body.style.backgroundColor = window.YourBrowserIsIE9 ?
                                       ? 'lightgreen' : 'lightblue';

else案例置于if条件下,然后尝试:

if (window.attachEvent) {
    eval('var YourBrowserIsIE = true;');
}
else{
    eval('var YourBrowserIsIE = false;');
}

由于您在if (window.attachEvent)条件内声明变量YourBrowserIsIE,因此如果上述条件失败,则该变量将保持未定义状态。

正如其他人所建议的那样,没有必要执行eval。

无论如何,如果您希望将代码设置为true/false;你可以执行这个

eval('var YourBrowserIsIE = window.attachEvent ? true : false;')

除非你分享实际问题,否则很难提供解决方案。

忽略使用对象推理是检测用户代理的一种严重缺陷的方法(许多浏览器复制IE的事件模型),因此非常不可靠,以下是如何在没有eval和最少代码的情况下完成您正在尝试的操作:

[…呃,请参阅Kooilnc的回答…]