JavaScript matematički sažetak ()

Funkcija JavaScript Math.abs () vraća apsolutnu vrijednost broja.

Apsolutna vrijednost broja x, označenog s | x | , definira se kao:

  • xako je x> 0
  • 0ako je x = 0
  • -xako je x <0

Sintaksa Math.abs()funkcije je:

 Math.abs(x)

abs(), koja je statična metoda, poziva se pomoću naziva Mathklase.

Parametri Math.abs ()

Math.abs()Funkcija uzima u:

  • x - A Numberčija se apsolutna vrijednost treba vratiti.

Povratna vrijednost iz Math.abs ()

  • Vraća apsolutnu vrijednost navedenog broja.
  • Vraća NaNako:
    • Prazan object
    • Nenumerički String
    • undefined/ prazna varijabla
    • Array s više elemenata
  • Vraća 0 ako:
    • Prazan String
    • Prazan Array
    • null

Primjer 1: Korištenje Math.abs () s brojem

 // 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

Izlaz

 57 0 2 3 420

Primjer 2: Korištenje Math.abs () s nebrojem

 // 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

Izlaz

 NaN NaN NaN NaN 0 0 0

Zanimljivi članci...