javascript 两个相同的字符串如何不相等?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8914902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do two identical strings not equal each other?
提问by qwertymk
Someone sent me this email:
有人给我发了这封电子邮件:
Why do both of these alert to false?
为什么这两个都警告错误?
alert('a?' == 'a');
alert('a?' === 'a');
Here's a demo
这是一个演示
JSFiddle DEMO
JSFiddle演示
回答by Adam Rackis
Is this a trick? Did you generate those a's
with some special unicode magic? I deleted the a's
and re-typed them, and now both alerts show true
, as they should
这是套路吗?你是a's
用一些特殊的 unicode 魔法生成的吗?我删除了a's
并重新输入了它们,现在两个警报都显示为true
,因为它们应该
回答by cambraca
The first a
of each is not actually a simple a
. If you position the cursor right after it and hit Backspace, you delete "something", and then it returns true
.
a
每个中的第一个实际上并不是一个简单的a
. 如果您将光标放在它的后面并按退格键,则会删除“某物”,然后返回true
。
I copied your a
string, this is what I get when running this code:
我复制了您的a
字符串,这是运行此代码时得到的结果:
$a='a?';
var_dump($a);
string(4) "a?"
See what's wrong here? The string length is 4.
看看这里出了什么问题?字符串长度为 4。
Furthermore, this:
此外,这:
echo base64_encode($a);
..returns:
..返回:
YeKAjA==
When, for a simple string with the letter a
, it should only be YQ==
.
当,对于带有字母 的简单字符串a
,它应该只是YQ==
。
The extra character is called a "ZERO WIDTH NON-JOINER".
额外的字符称为“零宽度非连接器”。
回答by Li0liQ
For the first 'a' console says:
对于第一个“a”控制台说:
'a?'.charCodeAt(0)
97
'a?'.charCodeAt(1)
8204
8204 seems to be a unicode value for Zero-width non-joiner
8204 似乎是零宽度非连接器的 unicode 值
Whilst for the second its:
第二个是:
'a'.charCodeAt(0)
97
'a'.charCodeAt(1)
NaN
It's natural that different strings are different :).
不同的字符串不同是很自然的:)。