development

JavaScript에서 양수에서 음수로?

big-blog 2020. 10. 15. 07:59
반응형

JavaScript에서 양수에서 음수로?


기본적으로 복근의 반대입니다. 만약 내가 가지고 있다면:

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

어떤 콘솔이든 항상 양수를 반환합니다. 이 문제를 어떻게 해결합니까?

만약 내가한다면:

if($this.find('.pdxslide-activeSlide').index() < slideNum-1){
_selector.animate({left:(-slideNum*sizes.images.width)+'px'},750,'InOutPDX')
}
else{
_selector.animate({left:(slideNum*sizes.images.width)+'px'},750,'InOutPDX')
}

그것은 작동하지만 "DRY"가 아니며 단지 코드 블록 전체를 가지고 -


Math.abs(num) => Always positive
-Math.abs(num) => Always negative

그러나 당신은 당신의 코드에 대해

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

발견 된 인덱스가 3이고 slideNum이 3
이면 3 <3-1 => false
이므로 slideNum 은 양수로 유지됩니다 .

나에게는 논리 오류처럼 보입니다.


복근의 반대는 Math.abs(num) * -1.


양수를 음수로 또는 음수를 양수로 반전하는 기본 공식 :

i - (i * 2)

JavaScript에서 음수 버전을 얻으려면 항상 ~비트 연산자 를 사용할 수 있습니다 .

예를 들어, a = 1000네거티브로 변환해야하는 경우 다음을 수행 할 수 있습니다.

a = ~a + 1;

결과적 a으로 -1000이됩니다.


제어가의 본문에 들어가는 것이 확실 if합니까? 에서와 같이 조건이 if사실입니까? 그렇지 않으면 if의지 의 몸 은 절대로 실행되지 slideNum않고 긍정적으로 남을 것입니다. 나는 이것이 아마도 당신이보고있는 것이라고 추측 할 것입니다.

Firebug에서 다음을 시도하면 작동하는 것 같습니다.

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

slideNum *= -1또한 작동해야합니다. 그래야합니다 Math.abs(slideNum) * -1.


var x = 100;
var negX = ( -x ); // => -100

Math.Abs ​​* -1을 사용하고 싶지 않다면이 간단한 if 문을 사용할 수 있습니다. : P

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

물론 이것을 다음과 같은 함수로 만들 수 있습니다.

function makeNegative(number) {
    if (number > 0) {
        number = -number;
    }
}

makeNegative (-3) => -3 makeNegative (5) => -5

Hope this helps! Math.abs will likely work for you but if it doesn't this little


var i = 10;
i = i / -1;

Result: -10

var i = -10;
i = i / -1;

Result: 10

If you divide by negative 1, it will always flip your number either way.


Use 0 - x

x being the number you want to invert


num * -1

This would do it for you.


In vanilla javascript

if(number > 0)
  return -1*number;

Where number above is the positive number you intend to convert

This code will convert just positive numbers to negative numbers simple by multiplying by -1

참고URL : https://stackoverflow.com/questions/5574144/positive-number-to-negative-number-in-javascript

반응형