Object.is() - JavaScript 编辑
The Object.is()
method determines whether two values are the same value.
Syntax
Object.is(value1, value2);
Parameters
value1
- The first value to compare.
value2
- The second value to compare.
Return value
A Boolean
indicating whether or not the two arguments are the same value.
Description
Object.is()
determines whether two values are the same value. Two values are the same if one of the following holds:
- both
undefined
- both
null
- both
true
or bothfalse
- both strings of the same length with the same characters in the same order
- both the same object (meaning both values reference the same object in memory)
- both numbers and
This is not the same as being equal according to the ==
operator. The ==
operator applies various coercions to both sides (if they are not the same Type) before testing for equality (resulting in such behavior as "" == false
being true
), but Object.is
doesn't coerce either value.
This is also not the same as being equal according to the ===
operator. The ===
operator (and the ==
operator as well) treats the number values -0
and +0
as equal and treats Number.NaN
as not equal to NaN
.
Examples
Using Object.is
Object.is('foo', 'foo'); // true
Object.is(window, window); // true
Object.is('foo', 'bar'); // false
Object.is([], []); // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(null, null); // true
// Special Cases
Object.is(0, -0); // false
Object.is(-0, -0); // true
Object.is(NaN, 0/0); // true
Polyfill
if (!Object.is) {
Object.defineProperty(Object, "is", {
value: function (x, y) {
// SameValue algorithm
if (x === y) { // Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
});
}
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Object.is' in that specification. |
Browser compatibility
BCD tables only load in the browser
See also
- Equality comparisons and sameness — a comparison of all three built-in sameness facilities
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论