jquery检查变量值

jquery check variable values

本文关键字:变量值 检查 jquery      更新时间:2023-09-26

在jQuery中,我有以下4个变量。

var add
var city
var state
var zip

我需要检查上述任何一个是否有值。如果没有一个值是正常的。如果它们都有一个值是确定的。

只需要检查其中至少有一个没有值。不确定什么是最有效的方法。

var check = [ add, city, state, zip ].every( function ( v ) { return !!v } )

只是为了炫耀。

说明:every 方法遍历所有数组,如果其中一个条件返回 false并立即停止循环,则返回false。如果所有循环都返回 true ,则返回true

PS:v代表"变量"。

var check = (function(a, b, c, d) {
    return !!a && !!b && !!c && !!d;
}(add, city, state, zip));
console.log(check);

另一种方法...今天让我们学习一些新技术!

这实际上将检查该值是否不为假。 其他任何东西都可以(字符串,数字,TRUE)。

if (yourVar)
{
    // if yourVar has value  then true other wise false.
}

希望这就是你需要的..

要检查我一个变量有一个值分配给它,你可以这样做:

var myVar
....
if (typeof myVar === 'undefined'){
  // here goes your code if the variable doesn't have a value
}
if(!add || !city || !state || !zip) {
    console.log('exists var with no value');
}
if( add.length == 0 || zip.length == 0 || city.length == 0 || state.length == 0) {    
    alert("at least one of the variables has no value");      
};   else if (add.length == 0 & zip.length == 0 & city.length == 0 & state.length == 0) {
         alert("all of the variables are empty");
     }; else { alert("okay"); }