两个相同的字符串如何彼此不相等?

时间:2021-06-12 11:30:15

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

3 个解决方案

#1


16  

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

这是一招吗?你用一些特殊的unicode魔法生成了那些吗?我删除了a并重新输入了它们,现在两个警报都显示为真实,正如它们应该的那样

Updated Fiddle

更新小提琴

#2


14  

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.

每个的第一个实际上并不简单。如果将光标放在其后面并按下Backspace,则删除“something”,然后返回true。

I copied your a string, this is what I get when running this code:

我复制了你的字符串,这是我在运行这段代码时得到的:

$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:

..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".

额外的角色被称为“ZERO WIDTH NON-JOINER”。

#3


6  

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 :).

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

#1


16  

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

这是一招吗?你用一些特殊的unicode魔法生成了那些吗?我删除了a并重新输入了它们,现在两个警报都显示为真实,正如它们应该的那样

Updated Fiddle

更新小提琴

#2


14  

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.

每个的第一个实际上并不简单。如果将光标放在其后面并按下Backspace,则删除“something”,然后返回true。

I copied your a string, this is what I get when running this code:

我复制了你的字符串,这是我在运行这段代码时得到的:

$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:

..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".

额外的角色被称为“ZERO WIDTH NON-JOINER”。

#3


6  

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 :).

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