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
4 Answers
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
版权声明:本文标题:variables - how to convert -1 to 1 with javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741276858a2369779.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论