非常教程

JavaScript参考手册

Math

Math.sign

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

语法

Math.sign(x)

参数

x一个数值。

返回值

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

描述

因为 signMath 的一个静态方法,所以你应该使用 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

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)

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络