JavaScript Math.abs () -funktio palauttaa luvun absoluuttisen arvon.
Luvun x absoluuttinen arvo, merkitty | x | , määritellään seuraavasti:
x
jos x> 00
jos x = 0-x
jos x <0
Math.abs()
Funktion syntaksi on:
Math.abs(x)
abs()
, joka on staattinen menetelmä, kutsutaan Math
luokan nimellä.
Math.abs () -parametrit
Math.abs()
Toiminto vie:
- x - A,
Number
jonka absoluuttinen arvo on palautettava.
Palautusarvo Math.abs: ltä ()
- Palauttaa määritetyn luvun absoluuttisen arvon.
- Palauttaa,
NaN
jos:- Tyhjä
object
- Ei numeerinen
String
undefined
/ tyhjä muuttujaArray
jossa on enemmän kuin yksi elementti
- Tyhjä
- Palauttaa 0, jos:
- Tyhjä
String
- Tyhjä
Array
null
- Tyhjä
Esimerkki 1: Math.abs (): n ja numeron käyttö
// Using Math.abs() with Number value1 = Math.abs(57); console.log(value1); // 57 value2 = Math.abs(0); console.log(value2); // 0 value3 = Math.abs(-2); console.log(value3); // 2 // Using Math.abs() with numeric non-Number // single item array value = Math.abs((-3)); console.log(value); // 3 // numeric string value = Math.abs("-420"); console.log(value); // 420
Tuotos
57 0 2 3 420
Esimerkki 2: Math.abs (): n käyttäminen ei-Numeron kanssa
// Using Math.abs() with non-Number // Math.abs() gives NaN for // empty object value = Math.abs(()); console.log(value); // NaN // non-numeric string value = Math.abs("Programiz"); console.log(value); // NaN // undefined value = Math.abs(undefined); console.log(value); // NaN // Array with>1 items value = Math.abs((1, 2, 3)); console.log(value); // NaN // Math.abs() gives 0 for // null objects console.log(Math.abs(null)); // 0 // empty string console.log(Math.abs("")); // 0 // empty array console.log(Math.abs(())); // 0
Tuotos
NaN NaN NaN NaN 0 0 0