简体   繁体   English

我可以使用三等号进行JavaScript字符串比较吗?

[英]Can I use triple equals for JavaScript string comparison?

This is an extremely basic question, I know, but I couldn't understand what's going on from Google and Stack Overflow. 我知道这是一个非常基本的问题,但我无法理解Google和Stack Overflow的情况。

I looked here and here to learn how to compare strings in JavaScript. 在这里这里查看了如何在JavaScript中比较字符串。 Neither mentioned triple equals ( === ) in their answers, and said that it's better to use your own function ( str1 < str2 ? -1 : str1 > str2 ). 他们都没有在答案中提到三等号( === ),并说最好使用自己的函数( str1 < str2 ? -1 : str1 > str2 )。

However, going through explanations about === in Stack Overflow ( here and here ), the answers contain string comparisons. 但是,在堆栈溢出( 此处此处 )中对===解释中,答案包含字符串比较。 From what I saw in those answers, === does work for string comparisons, so why wasn't it included in the string comparison answers? 从我在这些答案中看到的结果来看, ===确实适用于字符串比较,那么为什么不将其包含在字符串比较答案中?

I'm just trying to expand my knowledge in JavaScript. 我只是想扩展我的JavaScript知识。

Thanks for any insight! 感谢您的见解!

var str1 = "1";
var str2 = 1;
if (str1 == str2) {
      //Below code executes as it's true.
      console.log("Yes, value of both are equal.");
}

if (str1 === str2) {
     //Below code never executes as it's false.
     console.log("No, both are not equal as type differs.");
}

== compares value but === compares value as well as type. ==比较值,但===比较值和类型。 === can be used as string comparison but if you are sure that you are just comparing string then == should be sufficient. ===可以用作字符串比较,但是如果您确定只是比较字符串,则==就足够了。 === is just a better choice. ===只是一个更好的选择。

you can use both methods to compare strings, it just that you use === when you want to compare value AND type. 您可以使用两种方法来比较字符串,只是要比较值AND类型时使用=== what else is your query? 您的查询还有什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM