如何在 JavaScript 中检查空/未定义/空字符串?
JavaScript 中是否有 string.Empty
,或者只是检查 ""
的情况?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
JavaScript 中是否有 string.Empty
,或者只是检查 ""
的情况?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(30)
我用:
I use:
性能
我在 macOS v10.13.6 (High Sierra) 上对 18 个选定的解决方案进行了测试。 解决方案的工作方式略有不同(对于极端情况输入数据),如下面的代码片段所示。
结论
!str
、==
、===
和length 对于所有浏览器(A、B、C、G、I、J)都很快
test
、replace
)和的解决方案charAt
对于所有浏览器(H、L、M、P)来说都是最慢的,详细信息
在下面的代码片段中,我通过使用不同的输入参数来比较所选 18 种方法的结果
""
"a"
" "
- 空字符串,带字母的字符串和带空格的字符串[]
{}
f
- 数组、对象和函数0
1
NaN
Infinity
- 数字true
false
- 布尔null
<代码>未定义并非所有测试方法都支持所有输入情况。
然后,对于所有方法,我都会针对 Chrome v78.0.0、Safari v13.0.4 和 Firefox v71.0.0 浏览器执行速度测试用例
str = ""
- 您可以在您的计算机上运行测试 此处Performance
I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.
Conclusions
!str
,==
,===
andlength
are fast for all browsers (A,B,C,G,I,J)test
,replace
) andcharAt
are slowest for all browsers (H,L,M,P)Details
In the below snippet I compare results of chosen 18 methods by use different input parameters
""
"a"
" "
- empty string, string with letter and string with space[]
{}
f
- array, object and function0
1
NaN
Infinity
- numberstrue
false
- Booleannull
undefined
Not all tested methods support all input cases.
And then for all methods I perform speed test case
str = ""
for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here前面的所有答案都很好,但这个会更好。 使用双 NOT 运算符 (
!!
):或使用类型转换:
两者执行相同的功能。 将变量类型转换为布尔值,其中
str
是一个变量。对于
null
、undefined
、0
、000
、“”
,假
。对于除空字符串之外的所有字符串值(包括
"0"
和" "
等字符串),它返回true
>
All the previous answers are good, but this will be even better. Use dual NOT operators (
!!
):Or use type casting:
Both do the same function. Typecast the variable to Boolean, where
str
is a variable.It returns
false
fornull
,undefined
,0
,000
,""
,false
.It returns
true
for all string values other than the empty string (including strings like"0"
and" "
)您可以得到的最接近
str.Empty
(前提是 str 是一个字符串)是:The closest thing you can get to
str.Empty
(with the precondition that str is a String) is:如果您需要确保字符串不仅仅是一堆空格(我假设这是用于表单验证),您需要对空格进行替换。
If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.
空字符串、未定义、null、...
检查真实值:
检查 falsy 值:
空字符串(仅限!)
要检查是否为空字符串,请使用 进行严格相等比较/Operators/Strict_equality" rel="noreferrer">
===
运算符:要严格检查是否为空字符串,请使用
!==
运算符:Empty string, undefined, null, ...
To check for a truthy value:
To check for a falsy value:
Empty string (only!)
To check for exactly an empty string, compare for strict equality against
""
using the===
operator:To check for not an empty string strictly, use the
!==
operator:用于检查变量是否 falsey 或者它的长度属性是否等于零(对于字符串来说,意味着它是空的),我使用:
(请注意,字符串不是唯一具有
length
属性的变量,例如,数组也有它们。 )或者,您可以使用(不是这样)新的可选链接和箭头函数来简化:
它将检查长度,如果值为 null,则返回
undefined
,而不会引发错误。 在空值的情况下,零是假的,结果仍然有效。为了检查变量是否为 false 或者字符串是否仅包含空格或为空,我使用:
如果需要,您可以 monkey-patch
String
原型如下:请注意,monkey-patching 内置类型是有争议的,因为它无论出于何种原因,都可以破坏依赖于内置类型的现有结构的代码。
For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
(Note that strings aren't the only variables with a
length
attribute, arrays have them as well, for example.)Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
It will check the length, returning
undefined
in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
If you want, you can monkey-patch the
String
prototype like this:Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
非常通用的“一体化”函数(但不推荐):
但是,我不建议使用它,因为您的目标变量应该是特定类型(即字符串或数字,或对象?),因此应用与该变量相关的检查。
Very generic "All-In-One" Function (not recommended though):
However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.
您可以使用 lodash:
_.isEmpty(值)。
它涵盖了很多情况,例如
{}
、''
、null
、undefined
等。但它总是对于 JavaScript 原始数据类型,如
_.isEmpty(10)
或_.isEmpty(Number.MAX_VALUE)
均返回true
。You can use lodash:
_.isEmpty(value).
It covers a lot of cases like
{}
,''
,null
,undefined
, etc.But it always returns
true
forNumber
type of JavaScript primitive data types like_.isEmpty(10)
or_.isEmpty(Number.MAX_VALUE)
both returnstrue
.尝试:
Try:
我不会太担心最有效的方法。 使用最符合您意图的内容。 对我来说,通常是
strVar == ""
。根据 Constantin 的评论,如果 strVar 可能最终包含一个整数 0 值,那么这确实是 1那些澄清意图的情况。
I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually
strVar == ""
.As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.
或者以函数形式:
说明:
如果
input
为undefined
或null
则 null 合并?.
将导致input?.trim()?.length
将为undefined
或null
。 与0
进行或运算 (||
) 将得到0
。0
不是> 0
因此结果将为false
,即它是一个 nil 值。如果
input
为空或空格,则.trim()
将删除前导和结尾空格,这将使空输入保持不变,并将任何空格转换为空值。 那么空字符串的长度就是0
,并且如上,0
并不是>
,因此结果将为0
。 0false
,即它是空的或只有空格。如果
input
是任何其他字符串,它的长度将> 0 在调用.trim()
后,因此结果将为true
,即它不是 nil 值,也不是空值或只有空格。Or in function form:
Explanation:
If
input
isundefined
ornull
then the null coalescing?.
will result ininput?.trim()?.length
will beundefined
ornull
. ORing (||
) that with0
will give0
.0
is not> 0
therefore the result will befalse
, ie it IS a nil value.If
input
is empty or whitespace then.trim()
will remove leading and ending whitespace, which will keep an empty input the same, and convert any whitespace to an empty value. The length of an empty string is then0
, and as above,0
is not> 0
, therefore the result will befalse
, ie it IS empty or only whitespace.If
input
is any other string, it's length will be > 0 after calling.trim()
, and therefore the result will betrue
, ie it IS NOT a nil value, and it IS NOT empty or only whitespace.JavaScript 中没有任何东西代表空字符串。 检查
length
(如果您知道 var 始终是字符串)或""
There's nothing representing an empty string in JavaScript. Do a check against either
length
(if you know that the var will always be a string) or against""
这里有很多有用的信息,但在我看来,最重要的元素之一没有得到解决。
null
、undefined
和""
都是 falsy。当评估空字符串时,通常是因为您需要用其他东西替换它。
在这种情况下,您可能会出现以下行为。
考虑到这一点,可以返回字符串是否为
""
、null
或undefined
(无效字符串)的方法或函数) 与有效字符串的比较就这么简单:请注意,您可能还想
trim()
字符串,因为"" !== " "
。There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed.
null
,undefined
, and""
are all falsy.When evaluating an empty string, it's often because you need to replace it with something else.
In this case, you can expect the following behavior.
With that in mind, a method or function that can return whether or not a string is
""
,null
, orundefined
(an invalid string) versus a valid string is as simple as this:Please note, you probably also want to
trim()
the string since"" !== " "
.同时,我们可以有一个函数来检查所有“空”,例如 null、undefined、''、' '、{}、[]。
所以我就写了这个。
使用案例和结果。
Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, [].
So I just wrote this.
Use cases and results.
我对如果将非字符串和非空/空值传递给测试器函数会发生什么进行了一些研究。 正如许多人所知, (0 == "") 在 JavaScript 中是正确的,但由于 0 是一个值而不是空或 null,因此您可能需要测试它。
以下两个函数仅对于未定义、null、空/空白值返回 true,对于其他所有值(例如数字、布尔值、对象、表达式等)返回 false。
存在更复杂的示例,但这些示例很简单并且给出一致的结果。 无需测试未定义,因为它包含在 (value == null) 检查中。 您还可以通过将它们添加到 String 来模仿 C# 行为,如下所示
:想要将其放入 Strings 原型中,因为如果 String 类的实例为 null,则会出错:
我使用以下值数组进行了测试。 如果有疑问,您可以循环它来测试您的功能。
I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.
The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.
More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:
You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:
I tested with the following value array. You can loop it through to test your functions if in doubt.
检查
var a;
是否存在删除值中的错误空格,然后测试是否为空
check that
var a;
existtrim out the false spaces in the value, then test for emptiness
我通常使用这样的东西,
I usually use something like this,
另外,如果您将空格填充的字符串视为“空”。
您可以使用以下正则表达式来测试它:
Also, in case you consider a whitespace filled string as "empty".
You can test it with this regular expression:
如果不仅需要检测空字符串,还需要检测空字符串,我将添加到 Goral 的答案中:
If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:
从以下开始:
查看最后一个条件,如果 value == "",则其长度必须为0。因此丢弃它:
但是等等! 在 JavaScript 中,空字符串为 false。 因此, drop value == "":
并且 !undefined 为 true,因此不需要检查。 所以我们有:
我们不需要括号:
Starting with:
Looking at the last condition, if value == "", its length must be 0. Therefore drop it:
But wait! In JavaScript, an empty string is false. Therefore, drop value == "":
And !undefined is true, so that check isn't needed. So we have:
And we don't need parentheses:
我使用组合,最快的检查是最先的。
I use a combination, and the fastest checks are first.
我没有注意到考虑到字符串中空字符可能性的答案。 例如,如果我们有一个空字符串:
要测试它的空性,可以执行以下操作:
它适用于空字符串,并且适用于空字符串,并且所有字符串都可以访问它。 此外,它还可以扩展为包含其他 JavaScript 空字符或空白字符(即不间断空格、字节顺序标记、行/段落分隔符等)。
I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:
To test its nullness one could do something like this:
It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).
您还可以使用正则表达式:
检查是否为空或填充空格的字符串。
You could also go with regular expressions:
Checks for strings that are either empty or filled with whitespace.
很多答案,还有很多不同的可能性!
毫无疑问,对于快速而简单的实现,获胜者是:
if (!str.length) {...}
但是,还有许多其他示例可用。 我建议最好的功能方法:
我知道,有点过分了。
A lot of answers, and a lot of different possibilities!
Without a doubt for quick and simple implementation the winner is:
if (!str.length) {...}
However, as many other examples are available. The best functional method to go about this, I would suggest:
A bit excessive, I know.
我在这里没有看到一个好的答案(至少没有一个适合我的答案)
所以我决定回答自己:
value === undefined || 值 === null || value === "";
您需要开始检查它是否未定义。 否则你的方法可能会爆炸,然后你可以检查它是否等于 null 或者等于空字符串。
你不能有! 或仅
if(value)
因为如果您检查0
它会给您一个错误的答案(0 是错误的)。话虽如此,将其包装在如下方法中:
public static isEmpty(value: any): boolean {
返回值===未定义|| 值 === null || 值===“”;
PS
.: 你不需要检查 typeof,因为它甚至在进入方法之前就会爆炸并抛出
I didn't see a good answer here (at least not an answer that fits for me)
So I decided to answer myself:
value === undefined || value === null || value === "";
You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.
You cannot have !! or only
if(value)
since if you check0
it's going to give you a false answer (0 is false).With that said, wrap it up in a method like:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.: You don't need to check typeof, since it would explode and throw even before it enters the method
尝试这个:
Try this:
所有这些答案都很好。
但我不能确定该变量是一个字符串,不仅仅包含空格(这对我来说很重要),并且可以包含“0”(字符串)。
我的版本:
jsfiddle 上的示例。
All these answers are nice.
But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).
My version:
Sample on jsfiddle.
使用空合并运算符修剪空白:
Trimming whitespace with the null-coalescing operator:
没有
isEmpty()
方法,您必须检查类型和长度:需要进行类型检查,以避免当
test
未定义时出现运行时错误 或null
。There's no
isEmpty()
method, you have to check for the type and the length:The type check is needed in order to avoid runtime errors when
test
isundefined
ornull
.