提问人:casademora 提问时间:10/1/2008 最后编辑:Mateen Ulhaqcasademora 更新时间:10/30/2023 访问量:5325080
如何在 JavaScript 中检查空/未定义/空字符串?
How do I check for an empty/undefined/null string in JavaScript?
答:
空字符串、未定义、null、...
要检查真实值,请执行以下操作:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
要检查虚假值:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
空字符串(仅!
要检查是否准确无空字符串,请与使用 ===
运算符进行严格相等性比较:""
if (strValue === "") {
// strValue was empty string
}
要严格检查不为空字符串,请使用 !==
运算符:
if (strValue !== "") {
// strValue was not an empty string
}
评论
=== ''
.length
.length
我不会太担心最有效的方法。使用最清楚你的意图。对我来说,这通常是.strVar == ""
根据 Constantin 的评论,如果 strVar 最终可以包含一个整数 0 值,那么这确实是那些意图澄清的情况之一。
评论
var s; // undefined
var s = ""; // ""
s.length // 0
JavaScript 中没有任何东西表示空字符串。对(如果您知道 var 将始终是字符串)或length
""
评论
There's nothing representing an empty string in JavaScript.
""
你能得到的最接近的东西(前提是 str 是一个字符串)是:str.Empty
if (!str.length) { ...
评论
str.Empty
length
如果你需要确保字符串不仅仅是一堆空格(我假设这是为了表单验证),你需要对空格进行替换。
if(str.replace(/\s/g,"") == ""){
}
评论
if(str.match(/\S/g)){}
str.match(/\S/)
/\S/.test(str)
str.match(/\S/)
.test()
我通常使用类似的东西:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
评论
==
运算符不严格。所以如果 ,可以是 、 、 、 、 等。str == ""
str
null
undefined
false
0
[]
您也可以使用正则表达式:
if((/^\s*$/).test(str)) { }
检查空字符串或用空格填充的字符串。
评论
我使用:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
评论
typeof
switch
if (typeof e == "undefined")
case typeof(e) == "undefined":
是错误的;匹配 的 ,而不是 的。显然,这是一个建议的编辑,得到了批准。原版仍然没有任何意义。也没有理由考虑 、 和 “空”。e
false
undefined
case typeof this == "undefined":
false
0
"0"
isEmpty("0")
"0"
为了检查变量是否为 falsey 或它的 length 属性是否等于零(对于字符串,这意味着它是空的),我使用:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(请注意,字符串并不是唯一具有长度
属性的变量,例如,数组也有它们。
同时,您可以使用(不是这样)新可选的链接和箭头函数来简化:
const isEmpty = (str) => (!str?.length);
它将检查长度,如果值为空,则返回,而不会引发错误。如果为空值,则为零,结果仍然有效。undefined
为了检查变量是否为 falsey,或者字符串是否仅包含空格或为空,我使用:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
如果你愿意,你可以像这样对原型进行猴子修补:String
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
请注意,猴子修补内置类型是有争议的,因为它可能会破坏依赖于内置类型现有结构的代码,无论出于何种原因。
评论
if (variable == constant value)
if blue is the sky
if (!str) { // i am sure str is empty null or undefined here if I'm sure it won't be another data type }
试试这个
str.value.length == 0
评论
"".value.length
将导致错误。它应该是str.length === 0
TypeError
str
undefined
null
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;
// Now you can check if your string is empty as like
if(plen==0)
{
alert('empty');
}
else
{
alert('you entered something');
}
}
<input type='text' id='pasword' />
这也是检查字段是否为空的通用方法。
之前的所有答案都很好,但这会更好。使用双 NOT 运算符 ():!!
if (!!str) {
// Some code here
}
或者使用类型转换:
if (Boolean(str)) {
// Code here
}
两者都执行相同的功能。将变量类型转换为布尔值,其中是一个变量。str
它返回 、 、 、 、 。
false
null
undefined
0
000
""
false
它返回除空字符串以外的所有字符串值(包括像 和 这样的字符串
true
"0"
" "
)
评论
if(str)
if(!!str)
var any = (!!str1 && !!str2 && !!str3)
!!str.trim()
Boolean(str)
if
false
true
if
!!
我使用组合,最快的检查是第一位的。
function isBlank(pString) {
if (!pString) {
return true;
}
// Checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
评论
忽略空格字符串,您可以使用它来检查 null、empty 和 undefined:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
它简明扼要,适用于未定义的属性,尽管它不是最易读的。
评论
undefined
null
我没有注意到一个考虑到字符串中空字符可能性的答案。例如,如果我们有一个 null 字符串:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
为了测试它的无效性,可以做这样的事情:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
它适用于空字符串和空字符串,并且所有字符串都可以访问。此外,它可以扩展为包含其他 JavaScript 空或空格字符(即不间断空格、字节顺序标记、行/段落分隔符等)。
评论
检查您是否没有尝试传递未定义的术语也是一个好主意。
function TestMe() {
if((typeof str != 'undefined') && str) {
alert(str);
}
};
TestMe();
var str = 'hello';
TestMe();
我通常会遇到这样的情况:当对象实例的字符串属性不为空时,我想做一些事情。这很好,只是该属性并不总是存在。
尝试:
if (str && str.trim().length) {
//...
}
评论
str.trim().length
会比 快 ,根据我自己的测试结果,大约快 1%。str.trim()
if (!str) { ... }
另一种方式,但我相信 bdukes 的答案是最好的。
var myString = 'hello';
if(myString.charAt(0)){
alert('no empty');
}
alert('empty');
所有这些答案都很好。
但是我不能确定变量是一个字符串,不只包含空格(这对我来说很重要),并且可以包含“0”(字符串)。
我的版本:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
jsfiddle 上的示例。
评论
empty(0)
empty(7)
empty("0")
false
empty(0)
true
empty
empty
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
PHP
'0'
empty
empty
我做了一些研究,如果你将一个非字符串和非空/空值传递给测试器函数会发生什么。众所周知,(0 == “”) 在 JavaScript 中为 true,但由于 0 是一个值,而不是空或 null,您可能需要对其进行测试。
以下两个函数仅对未定义、null、空/空格值返回 true,对其他所有值(如数字、布尔值、对象、表达式等)返回 false。
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
存在更复杂的示例,但这些示例很简单,并且给出了一致的结果。无需测试 undefined,因为它包含在 (value == null) 检查中。您还可以通过将 C# 行为添加到 String 中来模拟它们,如下所示:
String.IsNullOrEmpty = function (value) { ... }
你不想把它放在 Strings 原型中,因为如果 String-class 的实例为 null,它将出错:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error
我使用以下值数组进行了测试。如有疑问,您可以循环使用它来测试您的函数。
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
评论
此外,如果您认为空白填充的字符串为“空”。
您可以使用以下正则表达式对其进行测试:
!/\S/.test(string); // Returns true if blank.
我更喜欢使用非空白测试而不是空白
function isNotBlank(str) {
return (str && /^\s*$/.test(str));
}
评论
不要假定您检查的变量是字符串。不要假设如果这个 var 有长度,那么它就是一个字符串。
问题是:仔细考虑你的应用程序必须做什么和可以接受什么。构建健壮的东西。
如果你的方法/函数应该只处理一个非空字符串,那么测试参数是否是一个非空字符串,不要做一些“技巧”。
举个例子,如果你不仔细地遵循这里的一些建议,就会爆炸。
var getLastChar = function (str) {
if (str.length > 0)
return str.charAt(str.length - 1)
}
getLastChar('hello')
=> "o"
getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'
所以,我会坚持下去
if (myVar === '')
...
评论
我通常使用这样的东西,
if (!str.length) {
// Do something
}
评论
typeof variable != "undefined"
非常通用的“多合一”功能(但不推荐):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
但是,我不建议使用它,因为您的目标变量应该是特定类型(即字符串、数字或对象?),因此请应用相对于该变量的检查。
评论
if
var x =" ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
alert("ya it is blank")
}
您也应该始终检查类型,因为 JavaScript 是一种鸭子类型语言,因此您可能不知道数据在过程中何时以及如何更改。所以,这是更好的解决方案:
let undefinedStr;
if (!undefinedStr) {
console.log("String is undefined");
}
let emptyStr = "";
if (!emptyStr) {
console.log("String is empty");
}
let nullStr = null;
if (!nullStr) {
console.log("String is null");
}
评论
undefined
要检查它是否为空:
var str = "Hello World!";
if(str === ''){alert("THE string str is EMPTY");}
要检查它是否为字符串类型:
var str = "Hello World!";
if(typeof(str) === 'string'){alert("This is a String");}
评论
length
null
str = ''; str.length == 0
str.length == null
如果不仅需要检测空字符串,还需要检测空白字符串,我会补充 Goral 的答案:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
- 检查是否存在
var a;
剪掉 in 值,然后测试
false spaces
emptiness
if ((a)&&(a.trim()!='')) { // if variable a is not empty do this }
评论
" "
http://underscorejs.org/,Underscore.js JavaScript 库提供了一个非常有用的函数,用于检查空字符串和其他空对象。_.isEmpty()
参考: http://underscorejs.org/#isEmpty
isEmpty
如果可枚举对象不包含任何值(没有可枚举的 own-properties),则返回 true。对于字符串和类似数组的对象,_.isEmpty 检查 length 属性是否为 0。_.isEmpty(object)
_.isEmpty([1, 2, 3]);
=> 假
_.isEmpty({});
=> 真
其他非常有用的下划线.js函数包括:
- http://underscorejs.org/#isNull
_.isNull(object)
- http://underscorejs.org/#isUndefined
_.isUndefined(value)
- http://underscorejs.org/#has
_.has(object, key)
很多答案,还有很多不同的可能性!
毫无疑问,对于快速和简单的实施,获胜者是:if (!str.length) {...}
但是,还有许多其他示例可用。我建议,最好的功能方法:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
return true;
else
return false;
}
有点过分,我知道。
评论
str.length === 0
对于没有形式参数的任何函数,返回 true。
没有方法,您必须检查类型和长度:isEmpty()
if (typeof test === 'string' && test.length === 0){
...
为了避免在 is 或 时出现运行时错误,需要进行类型检查。test
undefined
null
评论
test === ""
您可以使用 lodash: _.isEmpty(值)。
它涵盖了很多情况,如、、、等。{}
''
null
undefined
但它总是返回 JavaScript 原始数据类型的类型,例如或两者都返回。true
Number
_.isEmpty(10)
_.isEmpty(Number.MAX_VALUE)
true
评论
_.isEmpty(" "); // => false
" "
_.isEmpty("");
您可以轻松地将其添加到 JavaScript 中的原生 String 对象中,并一遍又一遍地重用它......
如果您想检查空字符串,像下面的代码这样简单的东西可以为您完成这项工作:''
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
否则,如果您想同时检查空字符串和空格,则只需添加 ,如下面的代码所示:''
' '
trim()
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
你可以这样称呼它:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
评论
!(!!this.length)
!this
!this.trim()
您可以验证以下方法并了解其中的区别。
var j = undefined;
console.log((typeof j == 'undefined') ? "true":"false");
var j = null;
console.log((j == null) ? "true":"false");
var j = "";
console.log((!j) ? "true":"false");
var j = "Hi";
console.log((!j) ? "true":"false");
同时,我们可以有一个函数来检查所有“空”,如 null、undefined、''、''、{}、[]。 所以我就写了这个。
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
用例和结果。
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
试试这个:
export const isEmpty = string => (!string || !string.length);
以下正则表达式是另一种解决方案,可用于 null、空或未定义的字符串。
(/(null|undefined|^$)/).test(null)
我添加了这个解决方案,因为它可以进一步扩展以检查空或一些值,如下所示。以下正则表达式检查字符串可以为空、null、未定义或仅包含整数。
(/(null|undefined|^$|^\d+$)/).test()
评论
(/(null|undefined|^$)/).test("null")
我在这里没有看到一个好的答案(至少不是一个适合我的答案)
所以我决定回答自己:
value === undefined || value === null || value === "";
您需要开始检查它是否未定义。否则,您的方法可能会爆炸,然后您可以检查它是否等于 null 或等于空字符串。
你不能拥有!!或者只是因为如果你检查它会给你一个错误的答案(0 是错误的)。if(value)
0
话虽如此,请将其包装在以下方法中:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.:你不需要检查typeof,因为它甚至在进入方法之前就会爆炸并抛出
评论
性能
我在 macOS v10.13.6 (High Sierra) 上对 18 种选定的解决方案进行了测试。解决方案的工作方式略有不同(对于极端情况输入数据),这在下面的代码片段中有所介绍。
结论
- 基于 ,的简单解决方案适用于所有浏览器(A、B、C、G、I、J)
!str
==
===
length
- 基于正则表达式 (,) 的解决方案对于所有浏览器 (H、L、M、P) 来说是最慢的
test
replace
charAt
- 标记为“最快”的解决方案仅在一次测试运行中是最快的 - 但在许多运行中,它在“快速”解决方案组中发生了变化
详
在下面的代码片段中,我通过使用不同的输入参数比较了所选 18 种方法的结果
""
"a"
" "
- 空字符串、带字母的字符串和带空格的字符串[]
{}
f
- 数组、对象和函数0
1
NaN
Infinity
-数字true
false
-布尔null
undefined
并非所有测试方法都支持所有输入情况。
function A(str) {
let r=1;
if (!str)
r=0;
return r;
}
function B(str) {
let r=1;
if (str == "")
r=0;
return r;
}
function C(str) {
let r=1;
if (str === "")
r=0;
return r;
}
function D(str) {
let r=1;
if(!str || 0 === str.length)
r=0;
return r;
}
function E(str) {
let r=1;
if(!str || /^\s*$/.test(str))
r=0;
return r;
}
function F(str) {
let r=1;
if(!Boolean(str))
r=0;
return r;
}
function G(str) {
let r=1;
if(! ((typeof str != 'undefined') && str) )
r=0;
return r;
}
function H(str) {
let r=1;
if(!/\S/.test(str))
r=0;
return r;
}
function I(str) {
let r=1;
if (!str.length)
r=0;
return r;
}
function J(str) {
let r=1;
if(str.length <= 0)
r=0;
return r;
}
function K(str) {
let r=1;
if(str.length === 0 || !str.trim())
r=0;
return r;
}
function L(str) {
let r=1;
if ( str.replace(/\s/g,"") == "")
r=0;
return r;
}
function M(str) {
let r=1;
if((/^\s*$/).test(str))
r=0;
return r;
}
function N(str) {
let r=1;
if(!str || !str.trim().length)
r=0;
return r;
}
function O(str) {
let r=1;
if(!str || !str.trim())
r=0;
return r;
}
function P(str) {
let r=1;
if(!str.charAt(0))
r=0;
return r;
}
function Q(str) {
let r=1;
if(!str || (str.trim()==''))
r=0;
return r;
}
function R(str) {
let r=1;
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
r=0;
return r;
}
// --- TEST ---
console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`);
log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);
log2('I', I);
log2('J', J);
log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);
然后,对于所有方法,我为浏览器Chrome v78.0.0,Safari v13.0.4和Firefox v71.0.0执行速度测试用例 - 您可以在此处在计算机上运行测试str = ""
评论
开始于:
return (!value || value == undefined || value == "" || value.length == 0);
查看最后一个条件,如果 value == “”,则其长度必须为 0。因此,请放下它:
return (!value || value == undefined || value == "");
但是等等!在 JavaScript 中,空字符串为 false。因此,drop 值 == “”:
return (!value || value == undefined);
undefined 为 true,因此不需要检查。所以我们有:
return (!value);
而且我们不需要括号:
return !value
评论
value = false
value = 0
if ((input?.trim()?.length || 0) > 0) {
// input must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
或以函数形式:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
解释:
如果为 或,则 null 合并将导致 将是 或 。ORing() 将给出 . 不是 因此结果将是 ,即它是一个 nil 值。input
undefined
null
?.
input?.trim()?.length
undefined
null
||
0
0
0
> 0
false
如果为空或空格,则将删除前导和结束空格,这将使空输入保持不变,并将任何空格转换为空值。空字符串的长度为 ,如上所述,不是 ,因此结果将是 ,即它是空的或只是空格。input
.trim()
0
0
> 0
false
如果是任何其他字符串,则调用后其长度>将为 0,因此结果将是 ,即它不是零值,也不是空或只有空格。input
.trim()
true
评论
const isNilOrWhitespace = input => !input?.trim();
这里有很多有用的信息,但在我看来,最重要的因素之一没有得到解决。
null
、 、 和 都是假的。undefined
""
在计算空字符串时,通常是因为您需要将其替换为其他内容。
在这种情况下,您可以预期以下行为。
var a = ""
var b = null
var c = undefined
console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"
考虑到这一点,可以返回字符串是否为 、 或(无效字符串)与有效字符串的方法或函数就这么简单:""
null
undefined
const validStr = (str) => str ? true : false
validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true
请注意,您可能还想要字符串,因为 .trim()
"" !== " "
评论
js const emptStr = ""
js const notEmptyStr = " "
使用 null-coalescing 运算符修剪空格:
if (!str?.trim()) {
// do something...
}
评论
?.
.trim()
str
您可以使用 typeof 运算符和 length 方法进行检查。
const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0
好吧,检查这一点的最简单功能是......
const checkEmpty = string => (string.trim() === "") || !string.trim();
用法:
checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.
就是这么简单。:)
评论
" "
isBlank 函数的最终和最短变体:
/**
* Will return:
* False for: for all strings with chars
* True for: false, null, undefined, 0, 0.0, "", " ".
*
* @param str
* @returns {boolean}
*/
function isBlank(str){
return (!!!str || /^\s*$/.test(str));
}
// tests
console.log("isBlank TRUE variants:");
console.log(isBlank(false));
console.log(isBlank(undefined));
console.log(isBlank(null));
console.log(isBlank(0));
console.log(isBlank(0.0));
console.log(isBlank(""));
console.log(isBlank(" "));
console.log("isBlank FALSE variants:");
console.log(isBlank("0"));
console.log(isBlank("0.0"));
console.log(isBlank(" 0"));
console.log(isBlank("0 "));
console.log(isBlank("Test string"));
console.log(isBlank("true"));
console.log(isBlank("false"));
console.log(isBlank("null"));
console.log(isBlank("undefined"));
试试这个代码:
function isEmpty(strValue)
{
// Test whether strValue is empty
if (!strValue || strValue.trim() === "" ||
(strValue.trim()).length === 0) {
// Do something
}
}
评论
(strValue.trim()).length === 0)
strValue.trim() === ""
这是一个虚假的值。
第一个解决方案:
const str = "";
return str || "Hello"
第二种解决方案:
const str = "";
return (!!str) || "Hello"; // !!str is Boolean
第三种解决方案:
const str = "";
return (+str) || "Hello"; // !!str is Boolean
评论
NaN
falsy
以下是我用于处理此问题的一些自定义函数。以及代码运行方式的示例。
const v1 = 0
const v2 = '4'
const v2e = undefined
const v2e2 = null
const v3 = [1, 2, 3, 4]
const v3e = []
const v4 = true
const v4e = false
const v5 = {
test: 'value'
}
const v5e = {}
const v6 = 'NotEmpty'
const v6e = ''
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
function isEmpty(v, zeroIsEmpty = false) {
/**
* When doing a typeof check, null will always return "object" so we filter that out first
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null
*/
if (v === null) {
return true
}
if (v === true) {
return false
}
if (typeof v === 'object') {
return !Object.keys(v).length
}
if (isNumeric(v)) {
return zeroIsEmpty ? parseFloat(v) === 0 : false
}
return !v || !v.length || v.length < 1
}
console.log(isEmpty(v1), isEmpty(v1, true))
console.log(isEmpty(v2), isEmpty(v2e), isEmpty(v2e))
console.log(isEmpty(v3), isEmpty(v3e))
console.log(isEmpty(v4), isEmpty(v4e))
console.log(isEmpty(v5), isEmpty(v5e))
console.log(isEmpty(v6), isEmpty(v6e))
同样作为参考,这里是 Lodash isEmpty 的来源:
检查它是否为字符串类型,以及它是否不为空:
const isNonEmptyString = (val) => typeof val === 'string' && !!val
使用核心(阅读普通)javascript,我们可以利用 Object.is() 进行严格的相等性比较。下面是一个代码片段。
function validateString(arg) {
if (Object.is(arg, "") || Object.is(arg, null) || Object.is(arg, undefined)) {
return false;
}
return true;
}
以下是 JavaScript 规范:https://262.ecma-international.org/12.0/#sec-object.is
这是Mozilla文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
希望这会有所帮助。
完整的示例。用于类型 、 和Object.keys()
string
array
object
function isEmpty(input){
switch(typeof input){
case 'undefined': return true
case 'string':
case 'object':
return Object.keys(input).length == 0
case 'boolean':
case 'bigint':
case 'number': return input == 0
}
}
function log(...logs){
for(let i = 0;i < logs.length;i++){
if(i % 2 == 1){
console.log(logs[i - 1],'=', logs[i])
}
}
}
log(
isEmpty(), 'empty undefined', // true
isEmpty(''), 'empty string', // true
isEmpty('abc'), 'empty string', // false
isEmpty([]), 'empty array', // true
isEmpty([2,3]), 'empty array', // false
isEmpty({}), 'empty object', // true
isEmpty({a: 'abc'}), 'empty object', // false
isEmpty(false), 'empty boolean', // true
isEmpty(true), 'empty boolean', // false
isEmpty(0n), 'empty bigint', // true
isEmpty(2n), 'empty bigint', // false
isEmpty(0), 'empty number', // true
isEmpty(2), 'empty number' // false
)
评论
null
undefined
null
undefined