18

JavaScript 比较中应该使用哪个等号运算符(== vs ===)?表示它们基本相同,除了 ' ===' 还确保类型相等,因此 ' ==' 可能执行类型转换。在 Douglas Crockford 的JavaScript: The Good Parts中,建议始终避免使用 ' =='。但是,我想知道设计两组相等运算符的最初想法是什么。

你有没有看到使用' =='实际上比使用' ==='更合适的情况?

4

4 回答 4

18

Consider a situation when you compare numbers or strings:

if (4 === 4)
{
  // true
}

but

if (4 == "4")
{
  // true
}

and

if (4 === "4")
{
  // false
}

This applies to objects as well as arrays.

So in above cases, you have to make sensible choice whether to use == or ===

于 2010-01-25T14:28:20.333 回答
5

简单的答案是,当您希望在比较期间发生类型强制时,'==' 比 '===' 更有意义。

一个很好的例子是在 URL 查询字符串中传递的数字。例如,如果您对内容进行了分页,并且page查询参数包含当前页码,那么您可以检查当前页面,if (page == 1) ...即使pageis 实际上"1",不是1

于 2010-01-25T16:45:11.780 回答
3

I would suggest that there is no problem with using ==, but to understand when and why to use it (i.e. use === as a rule, and == when it serves a purpose). Essentially, == just gives you shorthand notation - instead of doing something like

if (vble === 0 || vble === "" || vble === null || vble === undefined || vble === false) ...

It's much easier to just write

if (vble == false) ...

(Or even easier to write)

if (!vble) ...

Of course there are more examples than just looking for "truthy" or "falsey" values.

Really, you just need to understand when and why to use == and ===, I don't see any reason why not to use == where it fits better...

Another example is using this shorthand to allow shorthand method calls:

function func(boolOptionNotCommonlyUsed) {
  if (boolOptionNotCommonlyUsed) { //equiv to boolOptionNotCommonlyUsed == true
    //do something we rarely do
  }
  //do whatever func usually does
}

func(); //we rarely use boolOptionNotCommonlyUsed, so allow calling without "false" as an arg
于 2010-01-25T14:31:15.530 回答
0

== compares whether the value of the 2 sides are the same or not.

=== compares whether the value and datatype of the 2 sides are the same or not.

Say we have

$var = 0;

if($var == false){
  // true because 0 is also read as false
}

if(!$var){
  // true because 0 is also read as false
}

if($var === false){
  // false because 0 is not the same datatype as false. (int vs bool)
}

if($var !== false){
  // true becuase 0 is not the same datatype as false. (int vs bool)
}

if($var === 0){
  // true, the value and datatype are the same.
}

you can check http://www.jonlee.ca/the-triple-equals-in-php/

于 2010-01-25T14:27:41.397 回答