Η συνάρτηση JavaScript Math.abs () επιστρέφει την απόλυτη τιμή ενός αριθμού.
Απόλυτη τιμή ενός αριθμού x, που υποδηλώνεται με | x | , ορίζεται ως:
x
εάν x> 00
αν x = 0-x
αν x <0
Η σύνταξη της Math.abs()
συνάρτησης είναι:
Math.abs(x)
abs()
, ως στατική μέθοδος, καλείται χρησιμοποιώντας το Math
όνομα κλάσης
Math.abs () Παράμετροι
Η Math.abs()
συνάρτηση περιλαμβάνει:
- x - Α του
Number
οποίου η απόλυτη τιμή πρέπει να επιστραφεί.
Επιστροφή τιμή από Math.abs ()
- Επιστρέφει την απόλυτη τιμή του καθορισμένου αριθμού.
- Επιστρέφει
NaN
εάν:- Αδειάζω
object
- Μη αριθμητικό
String
undefined
/ κενή μεταβλητήArray
με περισσότερα από ένα στοιχεία
- Αδειάζω
- Επιστρέφει 0 εάν:
- Αδειάζω
String
- Αδειάζω
Array
null
- Αδειάζω
Παράδειγμα 1: Χρήση Math.abs () με αριθμό
// 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
Παραγωγή
57 0 2 3 420
Παράδειγμα 2: Χρήση Math.abs () με μη αριθμό
// 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
Παραγωγή
NaN NaN NaN NaN 0 0 0