如何用javascript将-1转换为1?

发布于 2024-09-24 06:04:01 字数 282 浏览 1 评论 0 原文

如何用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 ...

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

命硬 2024-10-01 06:04:01
 count = Math.abs(count)
 // will give you the positive value of any negative number
 count = Math.abs(count)
 // will give you the positive value of any negative number
浮世清欢 2024-10-01 06:04:01

abs 函数将所有数字变为正数:即 Math.abs( -1 ) = 1

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

古镇旧梦 2024-10-01 06:04:01

替代方法(可能比 Math.abs 更快,未经测试):

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

请注意,javascript 中的按位运算始终为 32 位。

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.

稳稳的幸福 2024-10-01 06:04:01

如果感兴趣的数字是输入...除了Math.abs(input)....

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

jsFiddle 示例

编辑:正如一些人指出的 -input-1 * input

上面使用了 Javascript条件运算符。这是唯一的三元(采用三个操作数)Javascript 运算符。

语法为:

condition ? expr1 : expr2

如果条件为真,则计算expr1,如果为假,则计算expr2

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文