Internet Explorer: “console is not defined” Error

前端 未结 9 1616
天涯浪人
天涯浪人 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 19:00

    You can use the below to give an extra degree of insurance that you've got all bases covered. Using typeof first will avoid any undefined errors. Using === will also ensure that the name of the type is actually the string "undefined". Finally, you'll want to add a parameter to the function signature (I chose logMsg arbitrarily) to ensure consistency, since you do pass whatever you want printed to the console to the log function. This also keep you intellisense accurate and avoids any warnings/errors in your JS aware IDE.

    if(!window.console || typeof console === "undefined") {
      var console = { log: function (logMsg) { } };
    }
    

提交回复
热议问题