How to check if only one value is not null in Javascript?

百般思念 提交于 2019-12-12 05:15:41

问题


Let's say I have 3 textboxes in cshtml. What I am trying to do in Javascript is the following:

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))

It is okay if it is a small number of textboxes, but if such number grows to 10+, it might become a hassle.

Is there any efficient way to implement such logic in Javascript regardless of how many textboxes we are dealing with?


回答1:


You can use .reduce:

var nonEmpty = [val1, val2, val3].reduce(((c, v) => c += (v !== "")), 0);
if (nonEmpty === 1) {
  // exactly one is not empty
}

Any other way of counting the non-empty inputs and checking that the count is equal to 1 would work too of course.

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);

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.




回答2:


just keep in th array values not null and then count how many remains :

var arr = ["hello", "", ""];

var result = arr.filter(x => x !== "").length;

if (result === 1) console.log("exactly one is not empty");



回答3:


You can directly check the textboxes for the values. If you are working in razor means you can use Jquery. Also this solution will work for any number of textboxes.

 var count=0;
 var isExactlyOneNotEmpty= 
    function(){
    $('input[name="text[]"]').each(function() {
        if($(this).val()!="")
        {
          ++count;
        }
    });
    if(count==1)
    return true
    else
    return false;
    }
 var check=isExactlyOneNotEmpty();
 alert(check);
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1" name="text[]">
<input type="text" id="text2" name="text[]" value="test">
<input type="text" id="text3" name="text[]">



回答4:


You could use the Exclusive OR (XOR) operator for that. Let's see what we can get with it:

However, the only result that doesn't fit your need is the last one (it returns true when all of them are also true).

To solve that, you could check if all values are not true at the same time. Summarizing, this expression does the trick:

if( !(val1 && val2 && val3) && (val1^val2^val3) )



来源:https://stackoverflow.com/questions/39981208/how-to-check-if-only-one-value-is-not-null-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!