La funció Math.sign()
retorna el signe d'un nombre, indicant si el nombre donat és positiu, negatiu o zero.
Sintaxi
Math.sign(x)
Paràmetres
x
- Un nombre.
Descripció
Com que sign()
és un mètode estàtic de Math
, sempre s'utilitza com Math.sign()
en comptes de com un mètode d'un objecte Math
creat (Math
no és un constructor).
Aquesta funció pot retornar 5 valors diferents, 1
, -1
, 0
, -0
, NaN
, que representen "nombre positiu", "nombre negatiu", "zero positiu", "zero negatiu" i NaN
respectivament.
L'argument passat a aquesta funció serà convertit al tipus de x
implícitament.
Exemples
Utilitzar 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
Math.sign = Math.sign || function(x) {
x = +x; // converteix a un nombre
if (x === 0 || isNaN(x)) {
return x;
}
return x > 0 ? 1 : -1;
}
Especificacions
Especificació | Estat | Comentaris |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Math.sign' in that specification. |
Standard | Definició inicial. |
Compatibilitat amb navegadors
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
Característica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Suport bàsic | 38 | 25 (25) | No support | 25 | No support |
Característica | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Suport bàsic | No support | No support | 25.0 (25) | No support | No support | No support |