Funkcja JavaScript Math.abs () zwraca wartość bezwzględną liczby.
Wartość bezwzględna liczby x, oznaczona przez | x | , definiuje się jako:
x
jeśli x> 00
jeśli x = 0-x
jeśli x <0
Składnia Math.abs()
funkcji to:
Math.abs(x)
abs()
jako metoda statyczna jest wywoływana przy użyciu Math
nazwy klasy.
Math.abs () Parametry
Math.abs()
Funkcja przyjmuje się:
- x - A,
Number
którego wartość bezwzględna ma zostać zwrócona.
Wartość zwracana z Math.abs ()
- Zwraca wartość bezwzględną określonej liczby.
- Zwraca,
NaN
jeśli:- Pusty
object
- Nieliczbowe
String
undefined
/ pusta zmiennaArray
z więcej niż jednym elementem
- Pusty
- Zwraca 0, jeśli:
- Pusty
String
- Pusty
Array
null
- Pusty
Przykład 1: Używanie Math.abs () z 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
Wynik
57 0 2 3 420
Przykład 2: Używanie Math.abs () z wartością inną niż Number
// 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
Wynik
NaN NaN NaN NaN 0 0 0