From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../reference/global_objects/object/is/index.html | 150 +++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/object/is/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/object/is') diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/is/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/is/index.html new file mode 100644 index 0000000000..ed905858d9 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/object/is/index.html @@ -0,0 +1,150 @@ +--- +title: Object.is() +slug: Web/JavaScript/Reference/Global_Objects/Object/is +tags: + - ECMAScript 2015 + - JavaScript + - 判断 + - 对象 + - 方法 + - 相等 +translation_of: Web/JavaScript/Reference/Global_Objects/Object/is +--- +
{{JSRef}}
+ +

Object.is() 方法判断两个值是否为同一个值

+ +

语法

+ +

+

Object.is(value1, value2);
+ + +

参数

+ +
+
value1
+
被比较的第一个值。
+
value2
+
被比较的第二个值。
+
+ +

返回值

+ +

一个 {{jsxref("Boolean")}} 类型标示两个参数是否是同一个值。

+ +

描述

+ +

Object.is() 方法判断两个值是否为同一个值。如果满足以下条件则两个值相等:

+ + + +

与{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} 运算不同。  == 运算符在判断相等前对两边的变量(如果它们不是同一类型) 进行强制转换 (这种行为的结果会将 "" == false 判断为 true), 而 Object.is不会强制转换两边的值。

+ +

与{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} 运算也不相同。 === 运算符 (也包括 == 运算符) 将数字 -0 和 +0 视为相等 ,而将{{jsxref("Number.NaN")}} 与{{jsxref("NaN")}}视为不相等.

+ +

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;
+    }
+  };
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ES2015', '#sec-object.is', 'Object.is')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-object.is', 'Object.is')}}{{Spec2('ESDraft')}}
+ +

例子

+ +

使用 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
+
+// 特例
+Object.is(0, -0);            // false
+Object.is(0, +0);            // true
+Object.is(-0, -0);           // true
+Object.is(NaN, 0/0);         // true
+
+ +

规范

+ +

+

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-object.is', 'Object.is')}}
+  
+ + +

浏览器兼容性

+ + + +

{{Compat("javascript.builtins.Object.is")}}

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf