了解JavaScript中的自定义abs函数

W3G*_*eek -2 javascript math ternary-operator

我希望我的逻辑没有缺陷,但我正在阅读JavaScript的权威指南,我不明白这个自定义abs函数是如何工作的......

function abs(x) {
  if (x >= 0) {
    return x;
  } else {
    return -x;
  }
}
Run Code Online (Sandbox Code Playgroud)

我使用三元运算符重新起草它以试图理解它...

var res = (x >= 0) ? x : -x;
return res;
Run Code Online (Sandbox Code Playgroud)

......但我仍然不知道它是如何运作的.

假设我使用-10作为x,它如何返回+10?标志如何反转?

Jos*_*eph 5

function abs(x) {
    if (x >= 0) {

        //If the number passed is greater than or equal to zero (positive)
        //return it back as is
        return x;

    } else {

        //If less than zero (negative)
        //return the negative of it (which makes it positive)
        // -(-10) === 10
        return -x;

    }
}
Run Code Online (Sandbox Code Playgroud)