Internet Explorer:“未定义控制台”错误 [英] Internet Explorer: "console is not defined" Error

查看:177
本文介绍了Internet Explorer:“未定义控制台”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我编写的一些JavaScript中使用了 console.log(),并且出现以下错误: console未定义在Internet Explorer中被抛出(在其他浏览器中工作正常)。

I was using console.log() in some JavaScript I wrote and an error of: console is not defined was thrown in Internet Explorer (worked fine in other browsers).

我已将其替换为:

if(console)console.log(...);

如果 console undefined ,我希望条件评估为 false 。因此,语句 console.log 将不会被执行,也不会抛出错误。

If console is undefined, I would expect the condition to evaluate as false. Ergo, the statement console.log wouldn't be executed and shouldn't throw an error.

相反,错误:控制台未在字符4中定义被抛出。

这是IE错误吗?或者if条件是否真的非法?这似乎很荒谬,因为如果 if(console)是非法的,那么 if(console == undefined)也应该是非法的。

Is this a IE bug? Or is that "if" condition really illegal? It seems absurd because if if (console) is illegal, then if (console==undefined) should be illegal too.

你应该如何检查 undefined 变量?

推荐答案

如果 console 本身根本不存在,则会抛出错误,因为您'访问未定义的变量。就像 if(abc){} 引发错误。

If console itself doesn't exist at all, it throws an error because you're accessing an undefined variable. Just like if(abc) {} throws an error.

console 位于窗口,而窗口 确实总是存在,这应该工作:

Since console resides in window, and window does always exist, this should work:

if(window.console) ...

基本上,访问不存在的属性是免费的,不会抛出错误(只是评估为 undefined ,如果条件,则失败。但是,访问未声明的变量是非法的。

Basically, accessing an property that doesn't exist is free and doesn't throw an error (it just evaluates to undefined, failing the if condition). However, it is illegal to access an undeclared variable.

这篇关于Internet Explorer:“未定义控制台”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆