英文:
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 || '')
||
将会把任何假值转换为空字符串。
只要变量保证只包含字符串、null
或undefined
,这个方法就有效。如果可能包含数字,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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论