Can I use triple equals for JavaScript string comparison?

浪尽此生 提交于 2021-02-18 20:54:05

问题


This is an extremely basic question, I know, but I couldn't understand what's going on from Google and Stack Overflow.

I looked here and here to learn how to compare strings in JavaScript. Neither mentioned triple equals (===) in their answers, and said that it's better to use your own function (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.

Thanks for any insight!


回答1:


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.




回答2:


you can use both methods to compare strings, it just that you use === when you want to compare value AND type. what else is your query?



来源:https://stackoverflow.com/questions/33858277/can-i-use-triple-equals-for-javascript-string-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!