隐含字符串比较,0 ='',但1 ='1' [英] Implied string comparison, 0='', but 1='1'

查看:100
本文介绍了隐含字符串比较,0 ='',但1 ='1'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was debugging something and discovered some strangeness in JavaScript:

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

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

It would make sense that an implied string comparison that 0 should = '0'. This is true for all non-zero values, but why not for zero?

推荐答案

根据关于 Javascript比较运算符


如果两个操作数的类型不同,JavaScript会转换
操作数,然后应用严格的
比较。如果任一操作数是
数或布尔值,则操作数是
转换为数字;如果
操作数是一个字符串,另一个是
转换为字符串

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

实际发生的是字符串正在转换为数字。
例如:

What's actually happening is that the strings are being converted to numbers. For example:

1 =='1'变为 1 = =数字('1')变为 1 == 1 true

然后尝试这个:
1 =='1。'变为 1 = =数字('1。')变为 1 == 1 true
如果他们成为字符串,那么你会得到'1'=='1。',这将是假的。

Then try this one: 1 == '1.' becomes 1 == Number('1.') becomes 1 == 1: true If they were becoming strings, then you'd get '1' == '1.', which would be false.

碰巧 Number('')== 0 ,因此 0 ==''是真的

这篇关于隐含字符串比较,0 ='',但1 ='1'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆