Object.is() 方法判断两个值是否是相同的值。
语法
Object.is(value1, value2);
参数
-
value1 - 第一个需要比较的值。
-
value2 - 第二个需要比较的值。
返回值
表示两个参数是否相同的布尔值 。
描述
Object.is() 判断两个值是否相同。如果下列任何一项成立,则两个值相同:
这种相等性判断逻辑和传统的 == 运算符会对它两边的操作数做隐式类型转换(如果它们类型不同),然后才进行相等性比较,(所以才会有类似 "" == false 等于 true 的现象),但 Object.is 不会做这种类型转换。
这与 NaN。
例子
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
// 特例
Object.is(0, -0); // false
Object.is(0, +0); // true
Object.is(-0, -0); // true
Object.is(NaN, 0/0); // true
Polyfill
if (!Object.is) {
Object.is = 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;
}
};
}
规范
| 规范 | 状态 | 备注 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Object.is |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) Object.is |
Draft |
浏览器兼容性
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
is |
Chrome Full support 30 | Edge Full support 12 | Firefox Full support 22 | IE No support No | Opera Full support Yes | Safari Full support 9 | WebView Android Full support Yes | Chrome Android Full support 30 | Firefox Android Full support 22 | Opera Android Full support Yes | Safari iOS Full support 9 | Samsung Internet Android Full support Yes | nodejs Full support 0.10 |
Legend
- Full support
- Full support
- No support
- No support
参见
- JavaScript 中的相等性判断 — JavaScript 中的三种相等性判断方法的比较