jQuery检查变量值
在jQuery中,我有以下4个变量。jQuery检查变量值
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
用于“可变”。
+1'PS:v代表“变量”'lol – rlemon 2012-04-19 16:48:59
if(!add || !city || !state || !zip) {
console.log('exists var with no value');
}
检查我一个变量的值将其分配给它,你可以这样做:
var myVar
....
if (typeof myVar === 'undefined'){
// here goes your code if the variable doesn't have a value
}
只需
if (yourVar)
{
// if yourVar has value then true other wise false.
}
希望这是你需要什么..
var check = (function(a, b, c, d) {
return !!a && !!b && !!c && !!d;
}(add, city, state, zip));
console.log(check);
另一种方法......让学习今天的一些新技术!
这实际上会检查值是否不为假。其他任何东西都可以(字符串,数字,真)。
呃,那只是丑陋的:p尽管很有趣^^ – 2012-04-19 16:49:08
顺便说一下,如果有空字符串,这也会返回false。 – 2012-04-20 07:02:16
哈哈,很好很简单,用jquery-esq touch,我喜欢它 – SpYk3HH 2012-04-20 17:37:40
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"); }
你确定在Javascript中没有以下四个变量吗? :P – rlemon 2012-04-20 12:30:37