Die JavaScript-Funktion Math.abs () gibt den absoluten Wert einer Zahl zurück.
Absolutwert einer Zahl x, bezeichnet mit | x | , ist definiert als:
xwenn x> 00wenn x = 0-xwenn x <0
Die Syntax der Math.abs()Funktion lautet:
Math.abs(x)
abs()Da es sich um eine statische Methode handelt, wird sie mit dem MathKlassennamen aufgerufen .
Math.abs () Parameter
Die Math.abs()Funktion umfasst:
- x - A,
Numberdessen absoluter Wert zurückgegeben werden soll.
Rückgabewert von Math.abs ()
- Gibt den absoluten Wert der angegebenen Zahl zurück.
- Gibt zurück,
NaNwenn:- Leer
object - Nicht numerisch
String undefined/ leere VariableArraymit mehr als einem Element
- Leer
- Gibt 0 zurück, wenn:
- Leer
String - Leer
Array null
- Leer
Beispiel 1: Verwenden von Math.abs () mit 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
Ausgabe
57 0 2 3 420
Beispiel 2: Verwenden von Math.abs () mit Nicht-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
Ausgabe
NaN NaN NaN NaN 0 0 0








