关于equals操作符:在javascript中,==和===有什么区别?

What is the difference between == and === in JavaScript?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
When would JavaScript == make more sense than ===?

以下方法在比较具有未定义值的字符串时的区别是什么?

1
2
3
4
5
 var x;
 if(x==undefined)
 {
  alert(x);
 }

1
2
3
4
if(x===undefined)
{
  alert(x);
}

在这种情况下,为什么我更喜欢第二种方法……请告诉我优势……


  • ==试图在测试值是否相同之前将其转换为相同的类型。"5" == 5
  • ===不这样做;它要求对象的类型相同才能相等。"5" !== 5

在这种情况下,结果是:

  • 如果xundefinednull,则x == undefined为真。
  • 只有当xundefined时,x === undefined才是真的。

如果希望对未定义和空值进行同等处理,则应首选第一个方法。其中一个常见的用法是可选的函数参数。

1
2
3
4
5
6
7
8
9
function greet(name, greeting) {
    if (name == undefined) name = 'World';
    if (greeting == undefined) greeting = 'Hello';
    alert(greeting + ' ' + name);
}

greet(); // alerts"Hello World"
greet("Bob"); // alerts"Hello Bob"
greet(null,"Goodbye"); // alerts"Goodbye World"

假设x=5,

=等于

x==8为假x==5是真的

===完全等于(值和类型)

x==5为真x=="5"为假

希望你能理解这个概念


==只是比较这两个值,如果它们的类型不同,则完成类型转换。

===比较值及其类型-因此此处不进行类型转换。


===也检查同一类型。您将通过几个例子了解:

1
(1 == '1') //Returns true

由于==不涉及类型,所以返回true。但是,如果您需要严格的类型检查,则可以使用===,因为只有当它是相同类型且值相同时,它才会返回true。

1
2
(1 === '1') //Returns false
(1 === 1) //Returns true
  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding
    positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything,
    including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===).

参考文献