JavaScript Math.abs () -funktionen returnerar det absoluta värdet för ett tal.
Absolut värde för ett tal x, betecknat med | x | , är definierad som:
x
om x> 00
om x = 0-x
om x <0
Math.abs()
Funktionens syntax är:
Math.abs(x)
abs()
, som är en statisk metod, kallas med hjälp av Math
klassnamnet.
Math.abs () Parametrar
Den Math.abs()
funktionen tar in:
- x - A
Number
vars absoluta värde ska returneras.
Returvärde från Math.abs ()
- Returnerar det absoluta värdet för det angivna numret.
- Returnerar
NaN
om:- Tömma
object
- Icke-numerisk
String
undefined
/ tom variabelArray
med mer än ett element
- Tömma
- Returnerar 0 om:
- Tömma
String
- Tömma
Array
null
- Tömma
Exempel 1: Använd Math.abs () med Number
// 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
Produktion
57 0 2 3 420
Exempel 2: Använda Math.abs () med icke-nummer
// 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
Produktion
NaN NaN NaN NaN 0 0 0