简体   繁体   English

如果 else 语句作为三元运算符,我将如何编写此语句

[英]How would I write this if else statement as ternary operator

This is kind of a beginners question but how would I write this JavaScript statement as a ternary operator?这是一个初学者的问题,但我如何将这个 JavaScript 语句编写为三元运算符? Or what would be the cleanest / most optimal way to write this?或者写这个的最干净/最优化的方式是什么?

if ($("#firstName,#lastName, #email, #message").filter(function() { return $(this).val(); }).length > 0) {
   $("label").css(labelAnimation[0]);
 } else {
   $("label").css(labelAnimation[1]);
 }

To keep things somewhat readable, put the boolean result into a variable first.为了保持可读性,首先将 boolean 结果放入变量中。 Then put the conditional inside the index lookup brackets:然后将条件放在索引查找括号内:

const anyInputsFilled = $("#firstName,#lastName,#email,#message")
    .filter(function () { return $(this).val(); })
    .length > 0;
$("label").css(labelAnimation[anyInputsFilled ? 0 : 1]);

I'd suggest extracting the values from labelAnimation first though, eg:我建议先从labelAnimation中提取值,例如:

const [anyFilledCSS, noneFilledCSS] = labelAnimation;
// ...
const anyInputsFilled = $("#firstName,#lastName,#email,#message")
    .filter(function () { return $(this).val(); })
    .length > 0;
$("label").css(anyInputsFilled ? anyFilledCSS : noneFilledCSS]);

You can do something like this你可以做这样的事情

$(
  "#firstName,#lastName,#email,#message").filter(
    function() { 
      return $(this).val(); 
    }
  ).length > 0
)
? $("label").css(labelAnimation[0]) : $("label").css(labelAnimation[1])

Or in one line:或者在一行中:

$("#firstName,#lastName,#email,#message").filter(function() {return $(this).val();}).length > 0) ? $("label").css(labelAnimation[0]) : $("label").css(labelAnimation[1])

You can write你可以写

$("label").css(labelAnimation[
    $("#firstName,#lastName,#email,#message").filter(() => $(this).val())
        .length > 0 
           ? 1
           : 0
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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