JavaScript-wiskunde abs ()

De JavaScript-functie Math.abs () retourneert de absolute waarde van een getal.

Absolute waarde van een getal x, aangegeven met | x | , is gedefinieerd als:

  • xals x> 0
  • 0als x = 0
  • -xals x <0

De syntaxis van de Math.abs()functie is:

 Math.abs(x)

abs(), zijnde een statische methode, wordt aangeroepen met behulp van de Mathklassenaam.

Math.abs () Parameters

De Math.abs()functie neemt:

  • x - A Numberwaarvan de absolute waarde moet worden geretourneerd.

Retourwaarde van Math.abs ()

  • Retourneert de absolute waarde van het opgegeven getal.
  • Retourneert NaNals:
    • Leeg object
    • Niet numeriek String
    • undefined/ lege variabele
    • Array met meer dan één element
  • Retourneert 0 als:
    • Leeg String
    • Leeg Array
    • null

Voorbeeld 1: Math.abs () gebruiken met nummer

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

Uitvoer

 57 0 2 3420

Voorbeeld 2: Math.abs () gebruiken zonder 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

Uitvoer

 NaN NaN NaN NaN 0 0 0

Interessante artikelen...