„JavaScript Math Abs“ ()

Funkcija „JavaScript Math.abs“ () pateikia absoliučią skaičiaus vertę.

Absoliuti skaičiaus x reikšmė, žymima | x | , apibrėžiamas kaip:

  • xjei x> 0
  • 0jei x = 0
  • -xjei x <0

Math.abs()Funkcijos sintaksė yra tokia:

 Math.abs(x)

abs(), kuris yra statinis metodas, vadinamas Mathklasės pavadinimu.

Math.abs () parametrai

Math.abs()Funkcija trunka:

  • x - A, Numberkurio absoliuti vertė turi būti grąžinta.

Grąžinimo vertė iš Math.abs ()

  • Grąžina absoliučią nurodyto skaičiaus vertę.
  • Grąžina, NaNjei:
    • Tuščia object
    • Ne skaitmeninis String
    • undefined/ tuščias kintamasis
    • Array turintys daugiau nei vieną elementą
  • Grąžina 0, jei:
    • Tuščia String
    • Tuščia Array
    • null

1 pavyzdys: Math.abs () naudojimas su skaičiumi

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

Rezultatas

 57 0 2 3 420

2 pavyzdys: Math.abs () naudojimas su ne skaičiumi

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

Rezultatas

 NaN NaN NaN NaN 0 0 0

Įdomios straipsniai...