在 JavaScript 中检查字符串相等性的正确方法是什么?

发布于 2024-09-16 10:34:55 字数 41 浏览 3 评论 0原文

在 JavaScript 中检查字符串之间是否相等的正确方法是什么?

What is the correct way to check for equality between Strings in JavaScript?

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

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

发布评论

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

评论(10

葬﹪忆之殇 2024-09-23 10:34:56

始终 在您完全理解使用 ===== 运算符的差异和含义之前,请使用=== 运算符,因为它可以帮助您避免晦涩(不明显)的 bug 和 WTF。由于内部类型强制,“常规”== 运算符可能会产生非常意外的结果,因此始终推荐使用 === 方法。

为了深入了解这一点以及 Javascript 的其他“好与坏”部分,请阅读 Douglas Crockford 先生和他的作品。有一个很棒的 Google 技术讲座,他总结了很多有用的信息:http://www.youtube.com /watch?v=hQVTIJBZook


更新:

你凯尔·辛普森 (Kyle Simpson) 的《不知道 JS》系列非常出色(并且可以免费在线阅读)。该系列深入探讨了该语言中常见的被误解的领域,并解释了 Crockford 建议您避免的“不好的部分”。通过了解它们,您可以正确使用它们并避免陷阱。

Up & Going" 书包含关于 平等,具体总结了何时使用宽松 (== ) 与严格 (===) 运算符:

为了将大量细节归结为一些简单的要点,并帮助您了解在各种情况下是否使用 =====,以下是我的简单规则:

  • 如果比较中的任一值(又称边)可能是 truefalse 值,请避免 == 并使用 ===.
  • 如果比较中的任一值可以是这些特定值(0""[] - 空数组) ,避免 == 并使用 ===
  • 所有其他情况下,您可以安全地使用==。它不仅安全,而且在许多情况下它以提高可读性的方式简化了代码。

我仍然向那些不想花时间真正理解 Javascript 的开发人员推荐 Crockford 的演讲——对于偶尔使用 Javascript 的开发人员来说,这是一个很好的建议。

always Until you fully understand the differences and implications of using the == and === operators, use the === operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook


Update:

The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.

The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==) vs strict (===) operators:

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.

少女情怀诗 2024-09-23 10:34:56

如果您知道它们是字符串,则无需检查类型。

"a" == "b"

但请注意,字符串对象不会相等。

new String("a") == new String("a")

将返回 false。

调用 valueOf() 方法将其转换为 String 对象的原始类型,

new String("a").valueOf() == new String("a").valueOf()

将返回 true

If you know they are strings, then there's no need to check for type.

"a" == "b"

However, note that string objects will not be equal.

new String("a") == new String("a")

will return false.

Call the valueOf() method to convert it to a primitive for String objects,

new String("a").valueOf() == new String("a").valueOf()

will return true

茶花眉 2024-09-23 10:34:56

您可以使用 ===== 但最后一个以更简单的方式工作(src)

a == b (及其否定 !=

在此处输入图像描述

a === b (及其否定 !==

在此处输入图像描述

You can use == or === but last one works in more simple way (src)

a == b (and its negation !=)

enter image description here

a === b (and its negation !==)

enter image description here

梦里梦着梦中梦 2024-09-23 10:34:56

只是对答案的补充:如果所有这些方法都返回 false,即使字符串看起来相等,也可能在一个字符串的左侧和/或右侧存在空格。因此,只需在比较之前在字符串末尾添加 .trim() 即可:

if(s1.trim() === s2.trim())
{
    // your code
}

我花了几个小时试图找出问题所在。
希望这对某人有帮助!

Just one addition to answers: If all these methods return false, even if strings seem to be equal, it is possible that there is a whitespace to the left and or right of one string. So, just put a .trim() at the end of strings before comparing:

if(s1.trim() === s2.trim())
{
    // your code
}

I have lost hours trying to figure out what is wrong.
Hope this will help to someone!

一笔一画续写前缘 2024-09-23 10:34:56

导致我提出这个问题的是 paddingwhite-spaces

检查我的情况

 if (title === "LastName")
      doSomething();

,标题是 " LastName"

在此处输入图像描述

所以也许你必须使用像这样的trim函数

var title = $(this).text().trim();

what led me to this question is the padding and white-spaces

check my case

 if (title === "LastName")
      doSomething();

and title was " LastName"

enter image description here

so maybe you have to use trim function like this

var title = $(this).text().trim();
爱格式化 2024-09-23 10:34:56

实际上有两种方法可以在 javascript 中创建字符串。

  1. var str = 'Javascript'; 这将创建一个原始字符串值。

  2. var obj = new String('Javascript'); 这将创建一个包装对象
    类型为字符串

    typeof str // 字符串
    typeof obj // object

因此,检查相等性的最佳方法是使用 === 运算符,因为它会检查两个操作数的值和类型。

如果您想检查两个对象之间的相等性,那么使用 String.prototype.valueOf 是正确的方法。

new String('javascript').valueOf() == new String('javascript').valueOf()

There are actually two ways in which strings can be made in javascript.

  1. var str = 'Javascript'; This creates a primitive string value.

  2. var obj = new String('Javascript'); This creates a wrapper object
    of type String.

    typeof str // string
    typeof obj // object

So the best way to check for equality is using the === operator because it checks value as well as type of both operands.

If you want to check for equality between two objects then using String.prototype.valueOf is the correct way.

new String('javascript').valueOf() == new String('javascript').valueOf()
花间憩 2024-09-23 10:34:56

可以使用 JSON.stringify() 技巧检查字符串对象。

var me = new String("me");
var you = new String("me");
var isEquel = JSON.stringify(me) === JSON.stringify(you);
console.log(isEquel);

String Objects can be checked using JSON.stringify() trick.

var me = new String("me");
var you = new String("me");
var isEquel = JSON.stringify(me) === JSON.stringify(you);
console.log(isEquel);

晌融 2024-09-23 10:34:56

严格比较

要进行简单比较,请使用 === 检查严格相等。正如其他人所说,这样做的优点是最有效并减少出现错误或不确定代码的机会。来源:MDN 网络文档:严格平等

var a = "hello1";
var b = "hello2";
console.log("a === a?" + (a === a) + "|");
console.log("a === b?" + (a === b) + "|");

按字母顺序比较

如果要根据自然排序比较两个字符串以了解一个字符串是在另一个字符串之前还是之后,请使用 <><=>= 运算符。来源:MDN WebDocs for <><=>=

    var a = "hello1";
    var b = "hello2";
    console.log("a < a?" + (a < a) + "|");
    console.log("a < b?" + (a < b) + "|");
    console.log("a > b?" + (a > b) + "|");
    console.log("b > a?" + (b > a) + "|");

Strict Comparisons

To do simple comparison, use === to check for strict equality. As others stated, this has the advantages of being most efficient and reducing the chances of buggy or uncertain code. Source: MDN Web Docs: Strict Equality.

var a = "hello1";
var b = "hello2";
console.log("a === a?" + (a === a) + "|");
console.log("a === b?" + (a === b) + "|");

Alphabetical Comparisons

If you want to compare two strings to know if a string comes before or after another string, based on natural sorting, use the <, >, <=, and >= operators. Source: MDN WebDocs for <, >, <=, and >=.

    var a = "hello1";
    var b = "hello2";
    console.log("a < a?" + (a < a) + "|");
    console.log("a < b?" + (a < b) + "|");
    console.log("a > b?" + (a > b) + "|");
    console.log("b > a?" + (b > a) + "|");

_畞蕅 2024-09-23 10:34:56

考虑到两个字符串可能都很大,主要有两种方法按位搜索localeCompare

我推荐这个函数

function compareLargeStrings(a,b){
    if (a.length !== b.length) {
         return false;
    }
    return a.localeCompare(b) === 0;
}

Considering that both strings may be very large, there are 2 main approaches bitwise search and localeCompare

I recommed this function

function compareLargeStrings(a,b){
    if (a.length !== b.length) {
         return false;
    }
    return a.localeCompare(b) === 0;
}
々眼睛长脚气 2024-09-23 10:34:56

对于字符串,我们有一个受支持的方法localCompare,它在字符串比较中非常方便。 IMO,我们应该只使用它,不需要使事情复杂化。

用法:

const a = 'Hello'
const b = 'Hell'

a.localCompare(a) // 0
a.localCompare(b) // 1
b.localCompare(a) // -1

For strings, we have a supported method localCompare which is very handy in string comparison. IMO, we should just use it and doesn't need to complicate stuff.

Usage:

const a = 'Hello'
const b = 'Hell'

a.localCompare(a) // 0
a.localCompare(b) // 1
b.localCompare(a) // -1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文