JavaScript 没有内置的方法来检查一个值是否为空,创建一个值很容易。在这样做之前,我们应该定义这样一个方法。根据 JavaScript 的需要进行修改。
const isFalsy = value => !value;
isFalsy(null); // true
isFalsy(undefined); // true
isFalsy(0); // true
isFalsy(false); // true
isFalsy(''); // true
isFalsy(NaN); // true
const isEmptyCollection = value =>
(Array.isArray(value) || value === Object(value)) &&
!Object.keys(value).length;
isEmptyCollection([]); // true
isEmptyCollection({}); // true
const isWhitespaceString = value =>
typeof value === 'string' && /^s*$/.test(value);
isWhitespaceString(' '); // true
isWhitespaceString('
r'); // true
const isInvalidDate = value =>
value instanceof Date && Number.isNaN(value.getTime());
const isEmptySet = value => value instanceof Set && value.size === 0;
const isEmptyMap = value => value instanceof Map && value.size === 0;
isInvalidDate(new Date('hello')); // true
isEmptySet(new Set()); // true
isEmptyMap(new Map()); // true
const isFalsy = value => !value;
const isWhitespaceString = value => typeof value === 'string' && /^s*$/.test(value);
const isEmptyCollection = value =>
(Array.isArray(value) || value === Object(value)) &&
!Object.keys(value).length;
const isInvalidDate = value => value instanceof Date && Number.isNaN(value.getTime());
const isEmptySet = value => value instanceof Set && value.size === 0;
const isEmptyMap = value => value instanceof Map && value.size === 0;
const isBlank = value => {
if (isFalsy(value)) return true;
if (isWhitespaceString(value)) return true;
if (isEmptyCollection(value)) return true;
if (isInvalidDate(value)) return true;
if (isEmptySet(value)) return true;
if (isEmptyMap(value)) return true;
return false;
};
isBlank(null); // true
isBlank(undefined); // true
isBlank(0); // true
isBlank(false); // true
isBlank(''); // true
isBlank(' r
'); // true
isBlank(NaN); // true
isBlank([]); // true
isBlank({}); // true
isBlank(new Date('hello')); // true
isBlank(new Set()); // true
isBlank(new Map()); // true
本期就分享到这里,希望能与大家共同学习与交流。
原文:How can I check for a blank value in JavaScript? - 30 seconds of code
页面更新:2024-02-20
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号