JavaScript 中 == 和 === 有什么区别?
可能的重复:
Javascript === 与 == :哪个重要我使用“等于”运算符?
什么时候 JavaScript == 比 === 更有意义? < /p>
是将字符串与未定义值进行比较时以下方法之间的区别。
var x;
if(x==undefined)
{
alert(x);
}
为什么
if(x===undefined)
{
alert(x);
}
在这种情况下我应该更喜欢第二种方法..请让我知道优点..
Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
When would JavaScript == make more sense than ===?
What is the difference between below methods in comparing a string with undefined value.
var x;
if(x==undefined)
{
alert(x);
}
and
if(x===undefined)
{
alert(x);
}
Why should i prefer second method in this case.. Please let me know advantages..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
==
尝试将值转换为相同类型,然后测试它们是否相同。"5" == 5
===
不会这样做;它要求对象具有相同类型才相等。"5" !== 5
在这种情况下,结果是:
x
是undefined,
或x == undefined
将为 truenull
。x
为undefined
时,x === undefined
才会为 true。如果您希望同等对待 undefined 和 null,您应该更喜欢第一种方法。其常见用途之一是可选函数参数。
==
attempts to convert the values to the same type before testing if they're the same."5" == 5
===
does not do this; it requires objects to be of the same type to be equal."5" !== 5
In this case, the result is:
x == undefined
will be true ifx
isundefined
ornull
.x === undefined
will only be true ifx
isundefined
.You should prefer the first method if you'd like undefined and null to be treated equivalently. One common use of this is optional function arguments.
假设我们有 x=5,
== 等于
x==8 为 false
x==5 为 true
=== 完全等于(值和类型)
x===5 为 true
x==="5" 是 false
希望你理解这个概念
suppose we have x=5,
== is equal to
x==8 is false
x==5 is true
=== is exactly equal to (value and type)
x===5 is true
x==="5" is false
Hope you understand this concept
===
也会检查相同的类型。通过几个例子您就会明白:由于
==
不关心类型,因此返回 true。但是,如果您想要严格的类型检查,则可以使用===
因为只有在类型相同且值相同时才返回 true。参考
===
checks for the same type as well. You'll understand with a few examples:Since
==
doesn't bother with types, that returns true. However, if you want strict type checking, you'd use===
because that returns true only if the it's of the same type, and is the same value.Reference
== 只是比较两个值,如果它们是不同类型,则完成类型转换
=== 比较值及其类型 - 因此这里不会进行类型转换。
== is just comparing the two values, and if they are of different types, type conversion is done
=== compares the values and well as their types - so no type conversion will be done here.