简体   繁体   中英

how to optimize this piece of JS code?

Sorry JS newbie here:

    if (message.notify_one_day_out){
        $("#data\\[User\\]\\[notify_one_day_out\\]").val("1");
    }
    else{
        $("#data\\[User\\]\\[notify_one_day_out\\]").val("0");
    }  

The above code feels sloppy. How can I condense it? I know this is development fundamentals but can I do something like:

$("#data\\[User\\]\\[notify_one_day_out\\]").val(message.notify_one_day_out);
//this is actually a function call "$()" better reference it to avoid overhead
var el = $("#data\\[User\\]\\[notify_one_day_out\\]");

el.val( message.notify_one_day_out ? '1' : '0');

i suggest you turn those [] into dashes or underscores. that way it won't be that messy.

$("#data\\[User\\]\\[notify_one_day_out\\]").val(
               message.notify_one_day_out ? "1" : "0");

You can use ternary operator (also called conditional operator ):

$("#data\\[User\\]\\[notify_one_day_out\\]").val(
         message.notify_one_day_out ? '1' : '0' );

Here is prototype of ternary operator:

(expression) ? this if true : this if false;

Essentially it is shorthand of if-else statements.


You can read more about it here:

您可以使用三元运算符

$("#data\\[User\\]\\[notify_one_day_out\\]").val(message.notify_one_day_out ? "1" : "0");

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