Internet Explorer: “console is not defined” Error

前端 未结 9 1618
天涯浪人
天涯浪人 2020-12-05 18:33

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

9条回答
  •  长情又很酷
    2020-12-05 18:53

    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.

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

    if(window.console) ...
    

    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.

提交回复
热议问题