我如何将这个 if else 语句写成三元运算符
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]);
}
为了保持可读性,请先将布尔结果放入变量中。然后将条件放在索引查找括号内:
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
])
这是一个初学者问题,但我如何将这个 JavaScript 语句写成三元运算符? 或者什么是最简洁/最佳的编写方式?
if ($("#firstName,#lastName, #email, #message").filter(function() { return $(this).val(); }).length > 0) {
$("label").css(labelAnimation[0]);
} else {
$("label").css(labelAnimation[1]);
}
为了保持可读性,请先将布尔结果放入变量中。然后将条件放在索引查找括号内:
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
])