如何使用javascript将-1转换为1?
var count = -1; //or any other number -2 -3 -4 -5 ...
或
var count = 1; //or any other number 2 3 4 5 ...
结果应该是
var count = 1; //or any other number 2 3 4 5 ...
答案 0 :(得分:17)
count = Math.abs(count)
// will give you the positive value of any negative number
答案 1 :(得分:3)
abs函数将所有数字都设为正数:即Math.abs(-1)= 1
答案 2 :(得分:3)
替代方法(可能比Math.abs
更快,未经测试):
count = -5;
alert((count ^ (count >> 31)) - (count >> 31));
请注意,javascript中的按位操作始终为32位。
答案 3 :(得分:0)
如果感兴趣的数量是input
...除 Math.abs(input)
....
var count = (input < 0 ? -input : input);
<强> jsFiddle example 强>
(编辑:有人指出-input
比-1 * input
更快
以上内容使用 Javascript conditional operator 。这是唯一的三元组(采用三个操作数)Javascript运算符。
语法为:
condition ? expr1 : expr2
如果condition
为真,则会评估expr1
,如果评估了expr2
,则会对其进行评估。