[英]how to optimize this piece of JS code?
Sorry JS newbie here: 对不起,JS新手在这里:
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. 本质上,它是if-else
语句的缩写。
You can read more about it here: 你可以在这里读更多关于它的内容:
您可以使用三元运算符 。
$("#data\\[User\\]\\[notify_one_day_out\\]").val(message.notify_one_day_out ? "1" : "0");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.