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/math/sign/index.html | 152 +++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/math/sign/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/math/sign') diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/sign/index.html b/files/zh-cn/web/javascript/reference/global_objects/math/sign/index.html new file mode 100644 index 0000000000..ca7678c9f0 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/math/sign/index.html @@ -0,0 +1,152 @@ +--- +title: Math.sign() +slug: Web/JavaScript/Reference/Global_Objects/Math/sign +tags: + - JavaScript + - Math + - Math.sign() +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sign +--- +
{{JSRef}}
+ +
 
+ +

Math.sign() 函数返回一个数字的符号, 指示数字是正数,负数还是零。

+ +

语法

+ +
Math.sign(x);
+ +

参数

+ +
+
x
+
任意数字.
+
+ +

描述

+ +

因为 sign Math 的一个静态方法,所以你应该使用 Math.sign() ,而不是作为你创建的一个Math对象的一种方法 (Math不是一个构造函数)。

+ +

而不是作为您创建的Math对象的一种方法(Math不是构造函数)。

+ +

此函数共有5种返回值, 分别是 1, -1, 0, -0, NaN. 代表的各是正数, 负数, 正零, 负零, NaN

+ +

传入该函数的参数会被隐式转换成数字类型。

+ +

示例

+ +

使用Math.sign()

+ +
Math.sign(3);     //  1
+Math.sign(-3);    // -1
+Math.sign("-3");  // -1
+Math.sign(0);     //  0
+Math.sign(-0);    // -0
+Math.sign(NaN);   // NaN
+Math.sign("foo"); // NaN
+Math.sign();      // NaN
+
+ +

Polyfill

+ +
function sign(x) {
+    x = +x ;// convert to a number
+    if (x === 0 || isNaN(x))
+        return x;
+    return x > 0 ? 1 : -1;
+}
+ +

 

+ +
if (!Math.sign) {
+  Math.sign = function(x) {
+    // If x is NaN, the result is NaN.
+    // If x is -0, the result is -0.
+    // If x is +0, the result is +0.
+    // If x is negative and not -0, the result is -1.
+    // If x is positive and not +0, the result is +1.
+    x = +x; // convert to a number
+    if (x === 0 || isNaN(x)) {
+      return Number(x);
+    }
+    return x > 0 ? 1 : -1;
+  };
+}
+ +

 

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-math.sign', 'Math.sign')}}{{Spec2('ES6')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support38{{CompatGeckoDesktop("25")}}{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

相关链接

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