如何在JavaScript中比较字符串,使空字符串等于null

huangapple go评论48阅读模式
英文:

How to compare string in javascript so that empty equals null

问题

什么是可以实现此检查的最快速的代码 :

只有当两个字符串具有不同字符时,它们才不同?

所以

null == undefined == ''

现在我使用

if(!s1 && !!s2
||
!!s1 && !s2
||
!!s1 && !!s2 && s1 != s2
)

但不涵盖所有情况

英文:

what can be the fastest code to have this check :

two strings are different only if they have different characters ?

so that

null == undefined == ''

now i use

if(!s1 && !!s2 
||
!!s1 && !s2
||
!!s1 && !!s2 && s1 != s2
)

but does not cover all cases

答案1

得分: 2

(s1 || '') == (s2 || '')

||将会把任何假值转换为空字符串。

只要变量保证只包含字符串、nullundefined,这个方法就有效。如果可能包含数字,0也会被转换为空字符串,所以0 == ''也是成立的。

数值型字符串也是字符串,所以这个方法对它们同样有效。

英文:
(s1 || '') == (s2 || '')

|| will convert any falsey value to an empty string.

This will work as long as the variables are guaranteed to hold either a string, null, or undefined. If it can have a number, 0 will also be converted to an empty string, so 0 == '' would be true.

Numeric strings are strings, so this will still work for them.

huangapple
  • 本文由 发表于 2023年2月13日 23:07:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定