[JavaScript] Math.abs()

6156 단어 JavaScriptJavaScript

Math.abs()

  • The Math.abs() function returns the absolute value of a number.
  • That is, it returns x if x is positive or zero, and the negation of x if x is negative.

Usage

function difference(a, b) {
  return Math.abs(a - b);
}

console.log(difference(3, 5));
// expected output: 2

console.log(difference(5, 3));
// expected output: 2

console.log(difference(1.23456, 7.89012));
// expected output: 6.6555599999999995

Syntax

Math.abs(x)

Examples

Math.abs('-1');     // 1
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs('');       // 0
Math.abs([]);       // 0
Math.abs([2]);      // 2
Math.abs([1,2]);    // NaN
Math.abs({});       // NaN
Math.abs('string'); // NaN
Math.abs();         // NaN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs#examples

좋은 웹페이지 즐겨찾기