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
'development' 카테고리의 다른 글
UITextView 텍스트 콘텐츠가 맨 위에서 시작되지 않습니다. (0) | 2020.10.15 |
---|---|
쉘 스크립트 데몬을 만드는 가장 좋은 방법은 무엇입니까? (0) | 2020.10.15 |
base64로 인코딩 된 이미지 크기 (0) | 2020.10.14 |
클래스 외부에서 인스턴스 변수에 액세스 (0) | 2020.10.14 |
아포스트로피 앞에 \가 없습니다. (0) | 2020.10.14 |