Positive Number to Negative Number in JavaScript?

后端 未结 13 1639
误落风尘
误落风尘 2020-12-13 05:16

Basically, the reverse of abs. If I have:

if ($this.find(\'.pdxslide-activeSlide\').index() < slideNum - 1) {
  slideNum = -slideNum
}
console.log(slideNu         


        
相关标签:
13条回答
  • 2020-12-13 05:58
    Math.abs(num) => Always positive
    -Math.abs(num) => Always negative
    

    You do realize however, that for your code

    if($this.find('.pdxslide-activeSlide').index() < slideNum-1){ slideNum = -slideNum }
    console.log(slideNum)
    

    If the index found is 3 and slideNum is 3,
    then 3 < 3-1 => false
    so slideNum remains positive??

    It looks more like a logic error to me.

    0 讨论(0)
  • 2020-12-13 05:59

    It will convert negative array to positive or vice versa

    function negateOrPositive(arr) {
        arr.map(res => -res)
    };
    
    0 讨论(0)
  • 2020-12-13 06:02

    To get a negative version of a number in JavaScript you can always use the ~ bitwise operator.

    For example, if you have a = 1000 and you need to convert it to a negative, you could do the following:

    a = ~a + 1;
    

    Which would result in a being -1000.

    0 讨论(0)
  • 2020-12-13 06:06

    The basic formula to reverse positive to negative or negative to positive:

    i - (i * 2)
    
    0 讨论(0)
  • 2020-12-13 06:06

    Are you sure that control is going into the body of the if? As in does the condition in the if ever hold true? Because if it doesn't, the body of the if will never get executed and slideNum will remain positive. I'm going to hazard a guess that this is probably what you're seeing.

    If I try the following in Firebug, it seems to work:

    >>> i = 5; console.log(i); i = -i; console.log(i);
    5
    -5
    

    slideNum *= -1 should also work. As should Math.abs(slideNum) * -1.

    0 讨论(0)
  • 2020-12-13 06:06

    Javascript has a dedicated operator for this: unary negation.

    TL;DR: It's the minus sign!

    To negate a number, simply prefix it with - in the most intuitive possible way. No need to write a function, use Math.abs() multiply by -1 or use the bitwise operator.

    Unary negation works on number literals:

    let a = 10;  // a is `10`
    let b = -10; // b is `-10`
    

    It works with variables too:

    let x = 50;
    x = -x;      // x is now `-50`
    
    let y = -6;
    y = -y;      // y is now `6`
    

    You can even use it multiple times if you use the grouping operator (a.k.a. parentheses:

    l = 10;       // l is `10`
    m = -10;      // m is `-10`
    n = -(10);    // n is `-10`
    o = -(-(10)); // o is `10`
    p = -(-10);   // p is `10` (double negative makes a positive)
    

    All of the above works with a variable as well.

    0 讨论(0)
提交回复
热议问题