'\ n \\\'== 0是真的吗? [英] '\n\t\r' == 0 is true?

查看:144
本文介绍了'\ n \\\'== 0是真的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天当我用 == 进行一些实验时,我意外地发现\ n\t\r= = 0 。怎么样\ n \\\\\等于 0 ,或 false

Today when I was doing some experiments with ==, I accidentally found out that "\n\t\r" == 0. How on earth does "\n\t\r" equal to 0, or false?

我做的是:

var txt = "\n";  //new line
txt == 0;        //it gives me true

这真让我恼火。所以我做了更多:

And that really annoy me. So I did more:

var txt = "\r";  //"return"
txt == 0;        //true

var txt = "\t";  //"tab"
txt == 0;        //true

完全没有意义。怎么会发生?更疯狂的是:

It does not make sense, at all. How's that happen? And more crazy is this:

//Checking for variable declared or not

var txt ="\n\t\r";
if(txt!=false){
    console.log("Variable is declared.");
}else{
    console.log("Variable is not declared.");
}

它给我的是未声明变量。

如何等于 0 ,或 false ???

How is it equal to 0, or false???

推荐答案

这种行为可能会令人惊讶,但可以通过查看规范

This behaviour might be surprising but can be explained by having a look at the specification.

我们要看看什么与 等于运算符进行比较时发生。确切的算法在第11.9.3节中定义。

We have to look at the what happens when a comparison with the equals operator is performed. The exact algorithm is defined in section 11.9.3.

我们要看的步骤是#5:

The step we have to look at is #5:


5。如果类型(x)是字符串而类型(y)是数字,

返回比较结果 ToNumber(x)== y

5. If Type(x) is String and Type(y) is Number,
return the result of the comparison ToNumber(x) == y.

这意味着字符串\ n\ r\ t )首先转换为数字,然后与 0 进行比较。

That means the string "\n" ("\r", "\t") is converted to a number first and then compared against 0.

如何是一个转换为数字的字符串?这在第9.3.1节中有说明。简而言之,我们有:

How is a string converted to a number? This is explained in section 9.3.1. In short, we have:


的MV(数学值)> StringNumericLiteral ::: StrWhiteSpace 0

其中 StrWhiteSpace 定义为

StrWhiteSpace :::
    StrWhiteSpaceChar StrWhiteSpace_opt

StrWhiteSpaceChar :::
    WhiteSpace
    LineTerminator

这只是意味着包含空格字符和/或行终止符的字符串的数值为 0

第7.3节。

This just means that the numerical value of strings containing white space characters and/or a line terminator is 0.
Which characters are considered as white space characters is defined in section 7.3.

我们要看的步骤是#7:

The step we have to look at is #7:


7。如果Type(y)是布尔值,则返回比较结果 x == ToNumber(y)

布尔值如何转换为数字非常简单: true 变为 1 false 变为 0

How booleans are converted to numbers is pretty simple: true becomes 1 and false becomes 0.

之后我们正在比较一个字符串一个数字,如上所述。

Afterwards we are comparing a string against a number, which is explained above.

正如其他人所提到的,严格比较( == = )可以用来避免这个问题。实际上,如果你知道自己在做什么并且想要这种行为,你应该只使用正常比较。

As others have mentioned, strict comparison (===) can be used to avoid this "problem". Actually you should only be using the normal comparison if you know what you are doing and want this behaviour.

这篇关于'\ n \\\'== 0是真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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