' \ n \ t \ r' == 0是真的吗?

发布于 2025-02-12 03:54:14 字数 718 浏览 2 评论 0原文

今天,当我对==进行一些实验时,我意外地发现“ \ n \ t \ r” == 0“ \ n \ t \ r”等于0false如何?

我所做的是:

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

那真的很烦我。所以我做了更多:

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

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

这根本没有意义。那怎么了?更疯狂的是:

//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.");
}

它给我的是变量未声明。

它如何等于0false

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?

What I did is:

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.");
}

What it gives me is Variable is not declared.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

哆兒滾 2025-02-19 03:54:14

这种行为可能令人惊讶,但可以通过查看“规格” 来解释。

我们必须查看与执行。确切的算法在第11.9.3节

我构建了一个简单的工具来证明执行哪些算法步骤: https:// felix-kling。 de/js-loose-comparison/


string ==整数

我们必须查看的步骤是#5:

5。如果类型(x)是字符串,<代码>类型(y)是数字,
返回比较的结果tonumber(x)== y

这意味着字符串“ \ n”“ \ r”“ \ t”)首先转换为数字,然后对0

字符串如何转换为数字?这在

stringnumericliteral ::: strwhitespace的MV(数学值)是0

其中strwhitespace被定义为

StrWhiteSpace :::
    StrWhiteSpaceChar StrWhiteSpace_opt

StrWhiteSpaceChar :::
    WhiteSpace
    LineTerminator

这只是意味着包含白空间字符和/或行终端的字符串的数值为0
第7.3节中,将哪些字符视为白空间字符。


字符串==布尔值

我们必须查看的步骤是#7:

7。如果类型(y)是布尔值,请返回比较的结果x == tonumber(y)

布尔值如何将其转换为数字很简单:true变为 1 和false forse 变为 0 。

之后,我们将字符串与一个数字进行比较,这将在上面解释。


正如其他人提到的那样,可以使用严格的比较(===)来避免此“问题”。实际上,只有知道自己在做什么并且想要这种行为时,才应该使用普通比较。

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

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.

I built a simple tool to demonstrate which algorithm steps are executed: https://felix-kling.de/js-loose-comparison/


string == integer

The step we have to look at is #5:

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

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

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

The MV (mathematical value) of StringNumericLiteral ::: StrWhiteSpace is 0.

where StrWhiteSpace is defined as

StrWhiteSpace :::
    StrWhiteSpaceChar StrWhiteSpace_opt

StrWhiteSpaceChar :::
    WhiteSpace
    LineTerminator

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.


string == boolean

The step we have to look at is #7:

7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

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.

方觉久 2025-02-19 03:54:14

由于JavaScript是一种松散地打字的语言,因此它试图键入与对方的比较的第一面,以便它们相互匹配。

与整数相比,与整数相比,不包含数字的任何字符串变为0(在某些情况下),与布尔值相比。

轻度阅读材料。

Because JavaScript is a loosely typed language, it attempts to type cast your 1st side of the comparison to the other so that they would match each other.

Any string which does not contain a number, becomes 0 when compared to an integer, and becomes true (Except in certain situations), when compared to a Boolean.

Light reading material.

山色无中 2025-02-19 03:54:14

txt不是boolean,因此永远不会是false。它可以是不确定的

var txt ="\n\t\r";
if(txt !== undefined) { //or just: if (txt)
    console.log("Variable is declared.");
} else {
    console.log("Variable is not declared.");
}
//=> will log: 'Variable is declared.'

顺便说一句,声明变量可以是undefined(例如var txt;)。

如果您进行更严格的比较(使用===),您会看到

var txt = '\n'; txt === 0; //=> false
var txt = '\r'; txt === 0; //=> false
var txt = '\t'; txt === 0; //=> false

另请参见

txt is not a Boolean, so it will never be false. It can be undefined though.

var txt ="\n\t\r";
if(txt !== undefined) { //or just: if (txt)
    console.log("Variable is declared.");
} else {
    console.log("Variable is not declared.");
}
//=> will log: 'Variable is declared.'

By the way, a declared variable may be undefined (e.g. var txt;).

If you do a stricter comparison (without type coercion, using ===), you'll see that

var txt = '\n'; txt === 0; //=> false
var txt = '\r'; txt === 0; //=> false
var txt = '\t'; txt === 0; //=> false

See also

分开我的手 2025-02-19 03:54:14

原因是“ \ n \ t \ r”(“” 被视为空字符串。
如果您使用==它将返回true,但是如果您使用===它将返回false

如果要测试存在,则应使用类似

if(typeof strName !== 'undefined') {
    /*do something with strName*/
} else {
    /*do something without it*/
}

The reason is that "\n\t\r" just as " " are treated as empty strings.
If you use == it will return true but if you use === it will return false.

If you want to test for existence you should use something like

if(typeof strName !== 'undefined') {
    /*do something with strName*/
} else {
    /*do something without it*/
}
私藏温柔 2025-02-19 03:54:14

每当您使用==操作员并尝试将字符串与数字进行比较时,该字符串将首先转换为数字。因此:alert(“ \ n \ r” == 0)变为:arter(number(“ \ n \ r”)== 0)
数字结构很有趣。它将首先剥离空格,然后确定数字是否不是数字。如果NAN,则结果为“ nan”。如果字符串为空,则结果为0。

alert(Number()) alerts 0
alert(Number("")) alerts 0
alert(Number(" \n \r \n \t")) alerts 0
alert(Number("blah")) alerts NaN
alert(Number("0xFF")) alerts 255
alert(Number("1E6")) alerts 1000000

要检查结果是否是nan使用isnan(),

Thus: alert(isNaN("blah")) alerts true
Thus: alert(isNaN("")) alerts false
Thus: alert(isNaN("\n")) alerts false
Thus: alert(isNaN(" ")) alerts false

但是请注意,nan永远不会等于nan:

var nan=Number("geh");alert(nan==nan);  alerts false 

更新:

如果您想检查双方是否两边是nan,然后您首先将两者都转换为布尔值:

var nan=Number("geh");alert(!!nan==!!nan); alerts true

或更好

var nan=Number("geh");
alert(isNaN(nan)&& isNaN(nan));

Whenever you use the == operator and try to compare a string to a number, the string will first be converted to a number. Thus: alert("\n\r"==0) becomes: alert(Number("\n\r")==0)
The Number constructure is kind of interesting. It will first strip whitespace then decide if the number is a not a number or not. If NaN, then the result is "NaN". If the string is empty, then the result is 0.

alert(Number()) alerts 0
alert(Number("")) alerts 0
alert(Number(" \n \r \n \t")) alerts 0
alert(Number("blah")) alerts NaN
alert(Number("0xFF")) alerts 255
alert(Number("1E6")) alerts 1000000

To check if the result is NaN use isNaN()

Thus: alert(isNaN("blah")) alerts true
Thus: alert(isNaN("")) alerts false
Thus: alert(isNaN("\n")) alerts false
Thus: alert(isNaN(" ")) alerts false

however do note that NaN will never equal NaN:

var nan=Number("geh");alert(nan==nan);  alerts false 

Update:

if you want to check if both sides are NaN, then you'd convert both to boolean values first like so:

var nan=Number("geh");alert(!!nan==!!nan); alerts true

or better yet

var nan=Number("geh");
alert(isNaN(nan)&& isNaN(nan));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文