如何在 JavaScript 中通过过滤空白值来比较变量

How to compare variables with filtering blank values in JavaScript

本文关键字:空白 比较 变量 过滤 JavaScript      更新时间:2023-09-26

我有五个字段,分别具有相应的值:

var valOne = document.getElementById("one").value;
var valTwo = document.getElementById("two").value;
var valThree = document.getElementById("three").value;
var valFour = document.getElementById("four").value;
var valFive = document.getElementById("five").value;

现在,如果我只想为填充值设置条件,例如如果 valOnevalTwo 不为空而其他为空白,那么:

if(valOne == "1" && valTwo == "2")
{
   alert("match found");
}

如果 valOnevalThreevalFour 不为空而其他两个为空,则相同,则:

if(valOne == "1" && valThree == "2" && valFour == "4")
{
   alert("match found");
}

请注意,如果valOne不为空,则只会显示 1 个值以与其给定值进行比较。

意思是 1,2,3,4,5 对于 valOnevalTwovalThreevalFourvalFive 是固定的。

擅长JavaScript,所以一个简单的线索对我真的很有帮助。

我建议你使用这样的方法

function isValid( idArray, validValueArray )
{
   for( var counter = 0; counter < idArray.length; counter++)
   {
      var elem = document.getElementById( idArray[ counter ] );
      var value = elem ? elem.value : "";
      if ( value && value.length > 0 && value != validValueArray[ counter ]  )
      {
         return false;
      }
   }
   return true;
}
isValid( [ "one", "two", "three", "four" ], [ "1", "2", "3", "4" ] );

或者,您可以根据键和值传递 id 和值

var keyValues = {
   "one" : "1",
   "two" : "2",
   "three" : "3",
   "four" : "4"
}
isValid( keyValues );
function isValid( keyValues )
{
   for( var id in keyValues )
   {
      var elem = document.getElementById( id );
      var value = elem ? elem.value : "";
      if ( value && value.length > 0 && value != keyValues [ id]  )
      {
         return false;
      }
   }
   return true;
}