Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js 如何判空? 「空」包含了:空数组、空对象、空字符串、0、undefined、null、空 map、空 set , 都属于为空的数据【热度: 640】 #790

Open
yanlele opened this issue Jul 12, 2024 · 0 comments
Labels
JavaScript JavaScript 语法部分 PDD 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Jul 12, 2024

关键词:判断

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

function isEmpty(value) {
  // 空字符串
  if (typeof value === "string" && value.trim() === "") {
    return true;
  }
  // 空数组
  if (Array.isArray(value) && value.length === 0) {
    return true;
  }
  // 空对象(不包括 `null`)
  if (typeof value === "object" && value !== null && Object.keys(value).length === 0) {
    return true;
  }
  // 数字 0
  if (typeof value === "number" && value === 0) {
    return true;
  }
  // `undefined`
  if (typeof value === "undefined") {
    return true;
  }
  // `null`
  if (value === null) {
    return true;
  }
  // 空 `Map`
  if (value instanceof Map && value.size === 0) {
    return true;
  }
  // 空 `Set`
  if (value instanceof Set && value.size === 0) {
    return true;
  }

  return false;
}

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

const emptyStr = "";
const emptyArr = [];
const emptyObj = {};
const zero = 0;
const undef = undefined;
const nullVal = null;
const emptyMap = new Map();
const emptySet = new Set();

console.log(isEmpty(emptyStr));
console.log(isEmpty(emptyArr));
console.log(isEmpty(emptyObj));
console.log(isEmpty(zero));
console.log(isEmpty(undef));
console.log(isEmpty(nullVal));
console.log(isEmpty(emptyMap));
console.log(isEmpty(emptySet));
@yanlele yanlele added JavaScript JavaScript 语法部分 PDD 公司标签 labels Jul 12, 2024
@yanlele yanlele added this to the milestone Jul 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 语法部分 PDD 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant