简体   繁体   English

使变量值为正

[英]making a variable value positive

I have a variable that will sometimes be negative and sometimes positive. 我有一个变量,有时会是负数,有时是正数。

Before I use it I need to make it positive. 在我使用之前,我需要让它变得积极。 How can I accomplish this? 我怎么能做到这一点?

Use the Math.abs method. 使用Math.abs方法。

There is a comment below about using negation (thanks Kelly for making me think about that), and it is slightly faster vs the Math.abs over a large amount of conversions if you make a local reference to the Math.abs function (without the local reference Math.abs is much slower). 下面有一个关于使用否定的评论(感谢Kelly让我考虑到这一点),如果你对Math.abs函数进行本地引用,那么Math.abs大量的转换它会比Math.abs略快Math.abs (没有本地参考Math.abs要慢得多。

Look at the answer to this question for more detail. 请查看此问题答案以获取更多详细信息。 Over small numbers the difference is negligible, and I think Math.abs is a much cleaner way of "self documenting" the code. 小数字的差异可以忽略不计,我认为Math.abs是一种更清晰的“自我记录”代码的方式。

Between these two choices (thanks to @Kooilnc for the example): 在这两个选择之间(感谢@Kooilnc的例子):

Number.prototype.abs = function(){
    return Math.abs(this);
};

and

var negative = -23, 
    positive = -negative>0 ? -negative : negative;

go with the second (negation). 和第二个(否定)一起去。 It doesn't require a function call and the CPU can do it in very few instructions. 它不需要函数调用,CPU可以用很少的指令来完成。 Fast, easy, and efficient. 快速,简单,高效。

if (myvar < 0) {
  myvar = -myvar;
}

or 要么

myvar = Math.abs(myvar);

or, if you want to avoid function call (and branching), you can use this code: 或者,如果要避免函数调用(和分支),可以使用以下代码:

x = (x ^ (x >> 31)) - (x >> 31);

it's a bit "hackish" and it looks nice in some odd way :) but I would still stick with Math.abs (just wanted to show one more way of doing this) 它有点“hackish”,它在某种奇怪的方式看起来不错:)但我仍然坚持使用Math.abs (只想展示另一种方式)

btw, this works only if underlying javascript engine stores integers as 32bit, which is case in firefox 3.5 on my machine (which is 32bit, so it might not work on 64bit machine, haven't tested...) 顺便说一句,这只适用于底层的javascript引擎将整数存储为32位,这在我的机器上的firefox 3.5中是这种情况(32位,所以它可能无法在64位机器上运行,还没有测试过...)

This isn't a jQuery implementation but uses the Math library from Javascript 这不是jQuery实现,而是使用Javascript中的Math库

x = Math.abs(x); x = Math.abs(x);

If you don't feel like using Math.Abs you can you this simple if statement :P 如果您不想使用Math.Abs​​,您可以使用以下简单语句:P

if (x < 0) {
    x = -x;
}

Of course you could make this a function like this 当然你可以把它变成这样的功能

function makePositive(number) {
    if (number < 0) {
        number = -number;
    }
}

makepositive(-3) => 3 makepositive (5) => 5 makepositive(-3)=> 3 makepositive(5)=> 5

Hope this helps! 希望这可以帮助! Math.abs will likely work for you but if it doesn't this little Math.abs可能会对你有用,但如果不是这样的话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM