在项目开发中,我们经常会遇到需要判断变量是否为空的情况,下面web建站小编给大家简单介绍5种jQuery判断变量是否为空的代码!
1、利用length属性判断
var arr = [];
if (arr.length > 0) {
console.log("变量不为空");
} else {
console.log("变量为空");
}
2、利用if语句判断
var str = "";
if (str) {
console.log("变量不为空");
} else {
console.log("变量为空");
}
3、利用!==判断变量是否为undefined或null
var variable;
if (variable !== undefined && variable !== null) {
console.log("变量不为空");
} else {
console.log("变量为空");
}
4、$.trim方法判断字符串是否为空格
var str = " ";
if ($.trim(str).length > 0) {
console.log("变量不为空");
} else {
console.log("变量为空");
}
5、利用jQuery的isEmptyObject方法判断
var obj = {};
if (!$.isEmptyObject(obj)) {
console.log("变量不为空");
} else {
console.log("变量为空");
}