nop*_*ole 224 javascript boolean
以下显示"0"
在Javascript 中为false:
>>> "0" == false
true
>>> false == "0"
true
Run Code Online (Sandbox Code Playgroud)
那么为什么以下打印"ha"
?
>>> if ("0") console.log("ha")
ha
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 339
显示问题的表:
和==
故事的道德使用===
表生成信用:https://github.com/dorey/JavaScript-Equality-Table
jdi*_*jdi 246
原因是当您明确地执行操作时"0" == false
,双方都将转换为数字,然后执行比较.
执行:时if ("0") console.log("ha")
,正在测试字符串值.任何非空字符串都是true
,而空字符串是false
.
相等(==)
如果两个操作数的类型不同,则JavaScript转换操作数,然后应用严格比较.如果操作数是数字或布尔值,操作数将尽可能转换为数字; 否则,如果任一操作数是字符串,则另一个操作数将转换为字符串(如果可能).如果两个操作数都是对象,则JavaScript比较内部引用,当操作数引用内存中的同一对象时,这些内部引用相等.
(从比较运算符在Mozilla开发者网络)
Inc*_*ito 36
这是根据规格.
12.5 The if Statement ..... 2. If ToBoolean(GetValue(exprRef)) is true, then a. Return the result of evaluating the first Statement. 3. Else, ....
根据规范,ToBoolean是
抽象操作ToBoolean根据表11将其参数转换为Boolean类型的值:
该表说明了字符串:
如果参数是空String(其长度为零),则结果为false; 否则结果是真的
现在,解释为什么"0" == false
你应该读取等于运算符,它指出它从抽象操作GetValue(lref)
中获取其值与右侧相同.
其中将此相关部分描述为:
if IsPropertyReference(V), then a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get be the special [[Get]] internal method defined below. b. Return the result of calling the get internal method using base as its this value, and passing GetReferencedName(V) for the argument
或者换句话说,字符串具有原始基础,它回调内部get方法并最终看起来为false.
如果要使用GetValue操作来评估事物==
,如果要使用ToBoolean
,请使用===
(也称为"严格"等于运算符)
bob*_*nce 12
它是PHP的字符串"0"
是falsy(false-when-used-in-boolean-context).在JavaScript中,所有非空字符串都是真实的.
诀窍是,==
对布尔值没有在布尔上下文中进行求值,它会转换为数字,对于通过解析为十进制来完成的字符串.所以你得到Number 0
而不是真实的布尔值true
.
这是一个非常糟糕的语言设计,这是我们尽量不使用不幸运==
算符的原因之一.请===
改用.
// I usually do this:
x = "0" ;
if (!!+x) console.log('I am true');
else console.log('I am false');
// Essentially converting string to integer and then boolean.
Run Code Online (Sandbox Code Playgroud)
你周围的引号0
使它成为一个字符串,它被评估为真。
删除引号,它应该可以工作。
if (0) console.log("ha")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
161588 次 |
最近记录: |