Get the absolute value of a number in Javascript

后端 未结 5 1028
盖世英雄少女心
盖世英雄少女心 2020-12-13 08:34

I want to get the absolute value of a number in JavaScript. That is, drop the sign. I know mathematically I can do this by squaring the number then taking the square root, b

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 08:43

    Alternative solution

    Math.max(x,-x)
    

    let abs = x => Math.max(x,-x);
    
    console.log( abs(24), abs(-24) );

    Also the Rick answer can be shorted to x>0 ? x : -x

提交回复
热议问题