admin管理员组

文章数量:1278789

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 ...

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 ...
Share Improve this question edited Sep 19, 2010 at 22:56 ChristopheD 116k30 gold badges166 silver badges181 bronze badges asked Sep 19, 2010 at 22:26 faressoftfaressoft 19.7k44 gold badges107 silver badges149 bronze badges 1
  • 2 here's a question related to this one that is more focused on which of the answers below are faster: stackoverflow./questions/441893/… – lock Commented Sep 19, 2010 at 23:04
Add a ment  | 

4 Answers 4

Reset to default 17
 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.

本文标签: variableshow to convert 1 to 1 with javascriptStack Overflow