if (value == null) { /* value is nullish */ } if (value === undefined || value === null) { /* value is nullish */ } if (value == undefined) { /* value is nullish */ } if ((value ?? null) === null) { /* value is nullish */ }
检查值是否不为nullish
1 2 3 4
if (value != null) { /* value is not nullish, although it could be falsy */ } if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ } if (value != undefined) { /* value is not nullish, although it could be falsy */ } if ((value ?? null) !== null) { /* value is not nullish, although it could be falsy */ }
// 检查值是否大于等于0 [null, -1, 0, 1].forEach(num => { if (num != null && num >= 0) { console.log("%o is not nullish and greater than/equal to 0", num); } else { console.log("%o is bad", num); } });
// 检查值是否不是空字符串或仅包含空格的字符串 ["", " ", "hello"].forEach(str => { if (str && /\S/.test(str)) { console.log("%o is truthy and has non-whitespace characters", str); } else { console.log("%o is bad", str); } });
// 检查值是否不是空数组 [[], [1]].forEach(arr => { if (arr && arr.length) { console.log("%o is truthy and has one or more items", arr); } else { console.log("%o is bad", arr); } });
// 使用可选链操作符检查值是否不是空数组 [[], [1]].forEach(arr => { if (arr?.length) { console.log("%o is not nullish and has one or more items", arr); } else { console.log("%o is bad", arr); } });
// 检查值是否为空(包括null、undefined、空字符串、空数组、空对象) functionisEmpty(value) { return ( // null or undefined (value == null) || // has length and it's zero (value.hasOwnProperty('length') && value.length === 0) || // is an Object and has no keys (value.constructor === Object && Object.keys(value).length === 0) ); }
// 检查值是否为未定义或null functionisEmptySimple(value) { return (typeof value === "undefined" || value === null); }