我可以使用三等号进行JavaScript字符串比较吗? [英] Can I use triple equals for JavaScript string comparison?
问题描述
我知道,这是一个非常基本的问题,但是我无法理解Google和Stack Overflow的情况.
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?
我只是想扩展我的JavaScript知识.
I'm just trying to expand my knowledge in JavaScript.
感谢您的见解!
推荐答案
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.
这篇关于我可以使用三等号进行JavaScript字符串比较吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!