JavaScript matematični abs ()

Funkcija JavaScript Math.abs () vrne absolutno vrednost števila.

Absolutna vrednost števila x, označena z | x | , je opredeljen kot:

  • xče je x> 0
  • 0če je x = 0
  • -xče je x <0

Sintaksa Math.abs()funkcije je:

 Math.abs(x)

abs(), ki je statična metoda, se pokliče z Mathimenom razreda.

Parametri Math.abs ()

Math.abs()Funkcija je v:

  • x - A, Numberkaterega absolutna vrednost se vrne.

Vrnjena vrednost iz Math.abs ()

  • Vrne absolutno vrednost podanega števila.
  • Vrne, NaNče:
    • Prazno object
    • Nenumerično String
    • undefined/ prazna spremenljivka
    • Array z več kot enim elementom
  • Vrne 0, če:
    • Prazno String
    • Prazno Array
    • null

Primer 1: Uporaba Math.abs () s številko

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

Izhod

 57 0 2 3 420

Primer 2: Uporaba Math.abs () z neštevilko

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

Izhod

 NaN NaN NaN NaN 0 0 0

Zanimive Članki...