如何检查Javascript中是否只有一个值不为空? [英] How to check if only one value is not null in Javascript?
问题描述
假设我在 cshtml 中有 3 个文本框.我在 Javascript 中尝试做的是以下内容:
Let's say I have 3 textboxes in cshtml. What I am trying to do in Javascript is the following:
检查这 3 个值中的任何一个和 ONLY THEM 是否不为空.
Check if ANY OF those 3 values and ONLY THEM is not null.
我能想到的唯一方法是手动进行:
The only way I can think of is doing it manually:
if ((val1 & !val2 & !val3) || (!val1 & val2 & !val3) || (!val1 & !val2 & val3))
如果文本框数量少也没关系,但如果这样的数字增长到 10+,可能会变得很麻烦.
It is okay if it is a small number of textboxes, but if such number grows to 10+, it might become a hassle.
无论我们处理多少个文本框,有没有什么有效的方法可以在 Javascript 中实现这种逻辑?
推荐答案
你可以使用 .reduce
:
var nonEmpty = [val1, val2, val3].reduce(((c, v) => c += (v !== "")), 0);
if (nonEmpty === 1) {
// exactly one is not empty
}
任何其他计算非空输入并检查计数是否等于 1 的方法当然也可以.
Any other way of counting the non-empty inputs and checking that the count is equal to 1 would work too of course.
.reduce()
代码的作用是使用箭头函数",当值不是空字符串时,它会增加计数器 (c
).(如果你想检查 null,你可以这样做,而不是当然.)你也可以使用一个普通的老式函数:
What that .reduce()
code does is use an "arrow function" that increments a counter (c
) when a value is not the empty string. (If you want to check for null, you can do that instead of course.) You could use a plain old-fashioned function too:
var nonEmpty = [val1, val2, val3].reduce(function(c, v) {
return c += (v !== "");
}, 0);
.reduce()
函数传递了 2 个参数:回调函数和 c
的初始值(在本例中为零).返回值将是最后一次调用回调返回的 c
的 final 值.
The .reduce()
function is passed 2 parameters: that callback function, and the initial value of c
(zero in this case). The return value will be the final value of c
returned by the last call to the callback.
这篇关于如何检查Javascript中是否只有一个值不为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!