开发者

how to convert -1 to 1 with javascript?

开发者 https://www.devze.com 2023-01-16 15:24 出处:网络
how to convert -1 to 1 with javascript ? var count = -1; //or any other number -2 -3 -4 -5 ... or var count = 1; //or any other number 2 3 4 5 ...

how to convert -1 to 1 with javascript ?

var count = -1; //or any other number -2 -3 -4 -5 ...

or

var count = 1; //or any other number 2 3 4 5 ...

result should be

var count = 1; //or any other number 2 3 4 5开发者_如何学JAVA ...


 count = Math.abs(count)
 // will give you the positive value of any negative number


The abs function turns all numbers positive: i.e Math.abs( -1 ) = 1


Alternative approach (might be faster then Math.abs, untested):

count = -5;
alert((count ^ (count >> 31)) - (count >> 31));

Note that bitwise operations in javascript are always in 32-bit.


If the number of interest is input... In addition to Math.abs(input)....

var count = (input < 0 ? -input : input);

jsFiddle example

(edit: as Some pointed out -input is faster than -1 * input)

The above makes use of the Javascript conditional operator. This is the only ternary (taking three operands) Javascript operator.

The syntax is:

condition ? expr1 : expr2

If the condition is true, expr1 is evaluated, if it's fales expr2 is evaluated.

0

精彩评论

暂无评论...
验证码 换一张
取 消