简体   繁体   中英

What is window.console && console.log?

 if (open_date) {
        open_date = get_date_from_string(open_date);
        window.console && console.log(open_date);
        window.console && console.log(cancel_until);

What is window.console && console.log ? Does it have to be in the code? Through this script does not work on IE (all version) --> IE runs javascript only after pressing F12

The rightside-expression will only get evaluated if the leftside-expression is truthy . Thats how the logical AND operator works.

Its basically short for

if( window.console ) {
    console.log( open_date );
}

As you might guess correctly, it's a common pattern for this case, because the console object might not be available on every browser (especially mobiles).

1.) What is window.console && console.log ?

console.log refers to the console object used for debugging. for firefox i use firebug for example.

but if the console is not available the script will crash. so window.console checks if the console object is there and if so it uses its log function to print out some debug information.

2.) Does it have to be in the code?

no, its only for debugging purpose

window.console && console.log(open_date); 

The above code is just short for an if conditional statement. It doesn't have to be there. it is for debugging purposes. For most browsers, you can hit F-12 to open the browser debug console. Chrome has a debug console built in. Firefox has an extension called FireBug that you can use. Below is the equivalent statement without the '&&'.

if (window.console) console.log(open_date); 

I prefer to add the following code at the beginning of my javascript code so that I do not have to have these "if" statements all over the place. It really saves space and removes potential errors.

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

Jon Dvorak's comment above contains an elegant alternative way of doing this:

console = window.console || {log:function(){}}

Console.log is a logger for browser which logs the messages on browser console. EDIT: Console.log is not supported for lower versions of Internet Explorer

此条件用于防止IE上的错误...因为,不幸的是,在IE(版本8)中我们无法使用console.log(“”)....但是测试人员仍然在Chrome上查看日志...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM