数组或字符串的几种判空方式
js中常见的判空就是字符串或数组的判空了,尤其是前端,一般拿到后端数据,尤其是数组,在对数组进行一些操作(如map,filter等)时最好先判空下,以防是空导致js报错。
1.数组
空数组的判空是最常见的,空数组可以理解成 new Array()
,相当于声明了一个新的空数组,程序会自动在堆中开辟一块空间。需要注意的是,它与var a = []
生成的内存空间不是同一块,所以不相等。
1.1 arr.length
let arr = [];
if (arr.length == 0) {
console.log('数组是空的');
} else {
console.log('数组不为空');
}
1.2 JSON.stringify(arr) === []
var arr = [];
if (JSON.stringify(arr) === '[]') {
console.log('数组是空的');
} else {
console.log('数组不为空');
}
1.3 函数方式 (推荐: 兼容arr[-1] = ‘’)
function isEmptyObject(n) {
var i;
for (i in n) {
return !1;
}
return !0;
}
使用示例:
if (!isEmptyObject(arr)) {
console.log('数组是空的')
} else {
console.log('数组不为空')
}
2.字符串
在js
中,字符串一般会有三种形式, ''
,null
,undefined
,如果在已知变量为空的情况下,可以直接采用 if (string.length == 0)
这种形式。
2.1tyeof |null| ''
(推荐:兼容null,undefined)
function isEmpty(obj) {
if (typeof obj === 'undefined' || obj == null || obj == '') {
return true;
} else {
return false;
}
}
该方法目前使用的最多,关于typeof 是js 中提供的运算符,用来检测一个变量的类型。
使用示例
if (!isEmpty(value)) {
console.log('该字符串是:' + value);
} else {
console.log('该串是一个空串');
}
2.2 trim() 函数
function isEmpty(value) {
let str = value.strim()
if (str.length == 0) {
console.log('该字符串为空')
} else {
console.log('输入的字符串为:' + value)
}
}
2.3 正则表达式
var str = '';
if (str.replace(/(^\s*)|(\s*$)/g, "").length == 0) {
console.log('该字符串是空')
}