关键词:判断

以下是一个 JavaScript 方法,用于校验您提到的各种“为空”的场景:

 1function isEmpty(value) {
 2  // 空字符串
 3  if (typeof value === "string" && value.trim() === "") {
 4    return true;
 5  }
 6  // 空数组
 7  if (Array.isArray(value) && value.length === 0) {
 8    return true;
 9  }
10  // 空对象(不包括 `null`)
11  if (typeof value === "object" && value !== null && Object.keys(value).length === 0) {
12    return true;
13  }
14  // 数字 0
15  if (typeof value === "number" && value === 0) {
16    return true;
17  }
18  // `undefined`
19  if (typeof value === "undefined") {
20    return true;
21  }
22  // `null`
23  if (value === null) {
24    return true;
25  }
26  // 空 `Map`
27  if (value instanceof Map && value.size === 0) {
28    return true;
29  }
30  // 空 `Set`
31  if (value instanceof Set && value.size === 0) {
32    return true;
33  }
34
35  return false;
36}

您可以使用这个方法来检测各种值是否为空,例如:

 1const emptyStr = "";
 2const emptyArr = [];
 3const emptyObj = {};
 4const zero = 0;
 5const undef = undefined;
 6const nullVal = null;
 7const emptyMap = new Map();
 8const emptySet = new Set();
 9
10console.log(isEmpty(emptyStr));
11console.log(isEmpty(emptyArr));
12console.log(isEmpty(emptyObj));
13console.log(isEmpty(zero));
14console.log(isEmpty(undef));
15console.log(isEmpty(nullVal));
16console.log(isEmpty(emptyMap));
17console.log(isEmpty(emptySet));
个人笔记记录 2021 ~ 2025