[英]How can I change the if else statement in the function with Ternary operator in JavaScript?
[英]How would I write this if else statement as ternary operator
這是一個初學者的問題,但我如何將這個 JavaScript 語句編寫為三元運算符? 或者寫這個的最干凈/最優化的方式是什么?
if ($("#firstName,#lastName, #email, #message").filter(function() { return $(this).val(); }).length > 0) {
$("label").css(labelAnimation[0]);
} else {
$("label").css(labelAnimation[1]);
}
為了保持可讀性,首先將 boolean 結果放入變量中。 然后將條件放在索引查找括號內:
const anyInputsFilled = $("#firstName,#lastName,#email,#message")
.filter(function () { return $(this).val(); })
.length > 0;
$("label").css(labelAnimation[anyInputsFilled ? 0 : 1]);
我建議先從labelAnimation
中提取值,例如:
const [anyFilledCSS, noneFilledCSS] = labelAnimation;
// ...
const anyInputsFilled = $("#firstName,#lastName,#email,#message")
.filter(function () { return $(this).val(); })
.length > 0;
$("label").css(anyInputsFilled ? anyFilledCSS : noneFilledCSS]);
你可以做這樣的事情
$(
"#firstName,#lastName,#email,#message").filter(
function() {
return $(this).val();
}
).length > 0
)
? $("label").css(labelAnimation[0]) : $("label").css(labelAnimation[1])
或者在一行中:
$("#firstName,#lastName,#email,#message").filter(function() {return $(this).val();}).length > 0) ? $("label").css(labelAnimation[0]) : $("label").css(labelAnimation[1])
你可以寫
$("label").css(labelAnimation[
$("#firstName,#lastName,#email,#message").filter(() => $(this).val())
.length > 0
? 1
: 0
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.