配圖源自 Freepik
平時項目里常用 licia 或 lodash 的 isEmpty()
來判斷一個值是否為「空」每界。
除了對象捅僵、數(shù)組,也常用來判斷 null眨层、undefined 等原始值庙楚。
- 字符串、數(shù)組趴樱、類數(shù)組:若 length 為 0 返回 true馒闷。
- 對象:獲取本身可枚舉的 key(原型上的不算)酪捡,若 key length 為 0 返回 true。
對于 Falsy Value纳账,有時得翻文檔確認下:
null
undefined
false
''
0
0n
NaN
結(jié)果:
const {isEmpty} = require('licia')
isEmpty(null) // true
isEmpty(undefined) // true
isEmpty(false) // true
isEmpty('') // true
isEmpty(0) // true
isEmpty(0n) // true
isEmpty(NaN) // true
// 以上值 lodash.isEmpty() 結(jié)果相同逛薇。
對于 Number、Boolean疏虫、BigInt 類型的原始值永罚,isEmpty() 均返回 true。
lodash.isEmpty() 還支持判斷 Map/Set 類型卧秘,其 size 為 0 則返回 true呢袱。而 licia.isEmpty() 不支持的,不管 size 是否為 0 均返回 true斯议。
源碼:
// https://github.com/liriliri/licia/blob/master/src/isEmpty.js
_('isArrLike isArr isStr isArgs keys');
exports = function(val) {
if (val == null) return true;
if (isArrLike(val) && (isArr(val) || isStr(val) || isArgs(val))) {
return val.length === 0;
}
return keys(val).length === 0;
};
// https://github.com/liriliri/licia/blob/master/src/keys.js
_('has');
if (Object.keys && !LICIA_TEST) {
exports = Object.keys;
} else {
exports = function(obj) {
const ret = [];
for (const key in obj) {
if (has(obj, key)) ret.push(key);
}
return ret;
};
}
// https://github.com/liriliri/licia/blob/master/src/has.js
const hasOwnProp = Object.prototype.hasOwnProperty;
exports = function(obj, key) {
return hasOwnProp.call(obj, key);
};
非常簡單:
- 判斷 null产捞、undefined
- 判斷數(shù)組醇锚、類數(shù)組
- 使用 in 操作符哼御,獲取其自身可枚舉的屬性,再判斷 key length
對于原始值焊唬,in 操作會隱式轉(zhuǎn)換為包裝對象
Object(val)
恋昼,由于它本身沒有可枚舉屬性,所以 Number赶促、Boolean液肌、BigInt 等類型的值 isEmpty() 會返回 true。
lodash 差不多鸥滨,其支持的類型更豐富一下嗦哆,比如 ArrayBuffer、TypedArray婿滓,但項目一般很少判斷這類的老速,不多說了。https://github.com/lodash/lodash/blob/4.17.15/lodash.js#L11479