gpt4 book ai didi

javascript - 隐含的字符串比较,0= ='',但 1= ='1'

转载 作者:行者123 更新时间:2023-12-03 13:44:50 25 4
gpt4 key购买 nike

我正在调试一些东西,并在 JavaScript 中发现了一些奇怪之处:

alert(1=='') ==> false
alert(0=='') ==> true
alert(-1=='') ==> false

隐含的字符串比较 0 应该 = '0' 是有意义的。对于所有非零值都是如此,但为什么不为零呢?

最佳答案

根据 Javascript Comparison Operators 上的 Mozilla 文档

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string



实际发生的是字符串被转换为数字。
例如:
1 == '1'变成 1 == Number('1')变成 1 == 1 : true
然后试试这个: 1 == '1.'变成 1 == Number('1.')变成 1 == 1 : true如果它们变成字符串,那么你会得到 '1' == '1.' ,这将是错误的。

恰好 Number('') == 0 ,因此 0 == ''是真的

关于javascript - 隐含的字符串比较,0= ='',但 1= ='1',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/462663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com