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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:58:15  来源:igfitidea点击:

How do two identical strings not equal each other?

javascript

提问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'swith some special unicode magic? I deleted the a'sand re-typed them, and now both alerts show true, as they should

这是套路吗?你是a's用一些特殊的 unicode 魔法生成的吗?我删除了a's并重新输入了它们,现在两个警报都显示为true,因为它们应该

Updated Fiddle

更新的小提琴

回答by cambraca

The first aof 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 astring, 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 :).

不同的字符串不同是很自然的:)。