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

时间:2012-09-03 05:07:34

标签: javascript variables eval undefined

直接定义变量时,它可以正常工作。与下面的代码一样,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()定义变量,如下所示,但结果将显示错误,指出在非IE浏览器中未定义YourBrowserIsIE

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


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

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


==编辑==

很抱歉不清楚。上面提到的使用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>

4 个答案:

答案 0 :(得分:4)

  

但我希望尽可能减少代码

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

我看到了它的两个优点:

  1. 这是最小的
  2. 不需要eval
  3. 查看您的代码,我建议您根本不使用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';
    

答案 1 :(得分:1)

else个案置于if条件并尝试:

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

由于您在YourBrowserIsIE条件中声明变量if (window.attachEvent),如果上述条件失败,变量将保持未定义。

答案 2 :(得分:1)

正如其他人所说,没有必要执行eval。

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

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

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

答案 3 :(得分:1)

忽略使用对象推断是一种严重缺陷的方法来检测用户代理(许多浏览器复制IE的事件模型),因此非常不可靠,这里是你如何做你想做的事情而没有eval和最小代码:

[...呃,见Kooilnc的回答......]

相关问题