JavaScript matemático abs ()

La función JavaScript Math.abs () devuelve el valor absoluto de un número.

Valor absoluto de un número x, denotado por | x | , Se define como:

  • xsi x> 0
  • 0si x = 0
  • -xsi x <0

La sintaxis de la Math.abs()función es:

 Math.abs(x)

abs(), al ser un método estático, se llama usando el Mathnombre de la clase.

Parámetros de Math.abs ()

La Math.abs()función incluye:

  • x - A Numbercuyo valor absoluto se devolverá.

Valor de retorno de Math.abs ()

  • Devuelve el valor absoluto del número especificado.
  • Devuelve NaNsi:
    • Vacío object
    • No numérico String
    • undefined/ variable vacía
    • Array con más de un elemento
  • Devuelve 0 si:
    • Vacío String
    • Vacío Array
    • null

Ejemplo 1: uso de Math.abs () con 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

Salida

 57 0 2 3420

Ejemplo 2: uso de Math.abs () con no números

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

Salida

 NaN NaN NaN NaN 0 0 0

Articulos interesantes...