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.");
}
==
比较的是值,而===
同时比较的是值和类型。
===
可以用于字符串比较,但如果您确定只需比较字符串,则==
就足够了。===
只是一个更好的选择。
===
和==
之间的区别,那不是我的问题。 - Neta你可以使用两种方法来比较字符串,只是当你想要比较值和类型时,你使用===
。还有什么其他问题吗?
===
可以比较两个字符串,并返回true
或false
。你看到的其他例子是在讨论对字符串列表进行排序时如何进行比较。 - Pointy===
而不是==
没有任何优势。===
通常用于比较将会是多种类型的事物。例如:'0' !== 0
。我假设==
也更快,但我太懒了,无法找到支持这一点的基准测试。 - Rooster