首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Math.sign

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

语法

代码语言:javascript
复制
Math.sign(x)

参数

x一个数值。

返回值

代表给定参数符号的数字。如果参数为正数,负数,正零或负零,函数将分别返回1-10-0。否则,返回NaN

描述

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

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

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

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

示例

使用Math.sign()

代码语言:javascript
复制
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

代码语言:javascript
复制
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.
    return ((x > 0) - (x < 0)) || +x;
    // A more aesthetical persuado-representation is shown below
?   //
?   // ( (x > 0) ? 0 : 1 )  // if x is negative then negative one
?   //          +           // else (because you cant be both - and +)
?   // ( (x < 0) ? 0 : -1 ) // if x is positive then positive one
?   //         ||           // if x is 0, -0, or NaN, or not a number,
?   //         +x           // Then the result will be x, (or) if x is
?   //                      // not a number, then x converts to number
  };
}

在上面的polyfill中,不需要额外的类型来强制创建(x > 0) or (x < 0)数字,因为从彼此中减去它们会强制从布尔型转换为数字型。

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Math.sign' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'Math.sign' in that specification.

Living Standard

?

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

38

(Yes)

25

No

25

9

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

25

No

(Yes)

(Yes)

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com