比较字符串与localeCompare vs ===? [英] Comparing strings with localeCompare vs ===?

查看:105
本文介绍了比较字符串与localeCompare vs ===?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的最新JS项目遇到了一个非常奇怪的问题。我通常使用 === 来比较字符串,但是当比较两个不同对象的字符串属性时,即使它们是完全相同的字符串,我也是假的。我通过执行以下操作在我的Node.js解释器中对此进行了测试:

I ran into a pretty strange issue with my latest JS project. I usually compare strings using === but when comparing the string properties of two of different objects I got false even though they were the exact same strings. I tested this in my Node.js interpreter by doing the following:

> x = {str: 'hello'}
{ str: 'hello' }
> y = {str: 'hello'}
{ str: 'hello' }
> y.str === x.str
true

所以我无法弄清楚为什么我的代码不工作。但是,当我从使用 === 切换到 str1.localeCompare BOOM时,它可以正常工作。这两者之间的区别是什么?

So I couldnt figure out why my code wasnt working. But when I switch from using === to str1.localeCompare BOOM, it works. Whats the difference between the two?

推荐答案

=== 寻找字符串中的字节完全相同。

=== looks for exactly the same bytes in the strings.

.localeCompare()允许您可能要忽略的事实字符串中的某些差异(例如puncutation或变音符号或大小写)仍然允许它们进行比较,或者在决定哪个字符串在另一个之前时忽略某些差异。并且,它提供了许多选项来控制使用或未使用的比较功能。

.localeCompare() allows for the fact that you may want to ignore certain differences in the strings (such as puncutation or diacriticals or case) and still allow them to compare the same or you want to ignore certain differences when deciding which string is before the other. And, it provides lots of options to control what comparison features are or are not used.

如果您阅读 c> string.prototype.localeCompare() MDN文档 $ c>,您可以看到一大堆可以传递的选项来控制比较的工作方式。在没有特殊字符的普通ascii字符串中,所有情况都相同,你不太可能看到差异,但开始涉及变音或案例问题, localCompare()有更多功能和更多选项来控制比较。

If you read the MDN documentation for string.prototype.localeCompare(), you can see a whole bunch of options you can pass in to control how the compare works. On a plain ascii string with no special characters in it that are all the same case, you are unlikely to see a difference, but start getting into diacriticals or case issues and localCompare() has both more features and more options to control the comparison.

可用于控制比较的一些选项:

Some of the options available for controlling the comparison:


  1. 数字整理

  2. 变音灵敏度

  3. 忽略标点符号的能力

  4. 案例优先

  5. 控制大写或小写首先比较

  1. numeric collation
  2. diacritical sensitivity
  3. ability to ignore punctuation
  4. case first
  5. control whether upper or lower case compares first

此外, localeCompare()返回一个完全对齐的值,用于 .sort()回调。

In addition, localeCompare() returns a value (negative, 0 or positive) that is perfectly aligned to use with a .sort() callback.

这篇关于比较字符串与localeCompare vs ===?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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