Matematický JavaScript abs ()

Funkce JavaScript Math.abs () vrací absolutní hodnotu čísla.

Absolutní hodnota čísla x, označená | x | , je definován jako:

  • xpokud x> 0
  • 0pokud x = 0
  • -xpokud x <0

Syntaxe Math.abs()funkce je:

 Math.abs(x)

abs()jako statická metoda se volá pomocí názvu Mathtřídy.

Parametry Math.abs ()

Math.abs()Funkce trvá in:

  • x - A, Numberjehož absolutní hodnota má být vrácena.

Vrátit hodnotu z Math.abs ()

  • Vrátí absolutní hodnotu zadaného čísla.
  • Vrátí se, NaNpokud:
    • Prázdný object
    • Numerické String
    • undefined/ prázdná proměnná
    • Array s více než jedním prvkem
  • Vrátí 0, pokud:
    • Prázdný String
    • Prázdný Array
    • null

Příklad 1: Použití Math.abs () s číslem

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

Výstup

 57 0 2 3420

Příklad 2: Použití Math.abs () s non-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

Výstup

 NaN NaN NaN NaN 0 0 0

Zajímavé články...