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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3586775/
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-08-23 05:19:18  来源:igfitidea点击:

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

javascriptstring

提问by JSS

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

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

回答by STW

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

总是直到你完全理解的差异和使用的影响=====运营商,使用===运营商,因为它可以使你免于晦涩(非显而易见性)的错误和WTFs。==由于内部的类型强制,“常规”运算符可能会产生非常意外的结果,因此===始终推荐使用。

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

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



Update:

更新:

The You Don't Know JSseries 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.

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

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

Up & Going”一书包含一个关于Equality的部分,其中具体总结了何时使用松散 ( ==) 与严格 ( ===) 运算符:

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 trueor falsevalue, avoid ==and use ===.
  • If either value in a comparison could be of these specific values (0, "", or []-- empty array), avoid ==and use ===.
  • In allother 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.

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

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

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.

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

回答by Anurag

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,

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

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

will return true

会返回真

回答by akelec

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:

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

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

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

我花了几个小时试图弄清楚出了什么问题。希望这会对某人有所帮助!

回答by Basheer AL-MOMANI

what led me to this question is the paddingand white-spaces

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

check my case

检查我的情况

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

and title was " LastName"

标题是 " LastName"

enter image description here

在此处输入图片说明

so maybe you have to use trimfunction like this

所以也许你必须使用这样的trim功能

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

回答by ludico8

Unless you really know how coercion works, you should avoid ==and use the identity operator ===instead.But you should read this to understand how it works.

除非你真的知道强制是如何工作的,否则你应该避免==使用恒等运算符===但是您应该阅读本文以了解它是如何工作的

If you use ==, you let the language do some type coercion for you, so for example:

如果你使用==,你会让语言为你做一些类型强制,例如:

"1" == 1 // true
"0" == false // true
[] == false // true

As Douglas Crockford's said in his book:

正如道格拉斯·克罗克福德 (Douglas Crockford) 在他的书中所说:

It's always better use the identity operator.

最好使用身份运算符。

回答by Abhishek

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

实际上有两种方法可以在 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

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

  2. var obj = new String('Javascript');这将创建一个类型为 的包装对象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.valueOfis the correct way.

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

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

回答by Muhammad Usman

String Objectscan be checked using JSON.stringyfy()trick.

Objects可以使用JSON.stringyfy()技巧检查字符串。

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

回答by Nagibaba

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

考虑到两个字符串都可能非常大,主要有两种方法bitwise searchlocaleCompare

I recommed this function

我推荐了这个功能

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

回答by Pedro JR

The easiest way to do it is to use a ternary operator like so:

最简单的方法是使用三元运算符,如下所示:

 "was" == "was" ? true : false

but if the string you want to compare is in an array, you'll use the es6 filter

但是如果要比较的字符串在数组中,则将使用 es6 过滤器

let stringArray  = ["men", "boys", "girls", "sit", "can", "gotten"]
stringArray.filter(I=> I === boys ? 
stringArray.pop(indexOf(I)) : null)

the above will check your stringArray and whatever string that matches it from the array which in our case we chose "boys"

以上将检查您的 stringArray 以及与它匹配的任何字符串,在我们的例子中我们选择了“boys”

回答by Khorram Bin Salim Khondkar

I came up with a alternative solution during testing. you can use function on the string prototype.

我在测试期间想出了一个替代解决方案。您可以在字符串原型上使用函数。

String.prototype.betwenStr = function(one){

return JSON.stringify(new String(this)) === JSON.stringify(new String(one));

}


 //call it
 "hello world".betweenStr("hello world"); //returns boolean 
 //value

works fine in chrome browsers

在 chrome 浏览器中工作正常