숫자가 두 값 사이에 있는지 확인하는 방법은 무엇입니까?
자바스크립트에서, 나는 윈도우 크기가 500px보다 크면 브라우저에게 무언가를 하라고 말하고 있습니다.저는 그렇게 합니다.
if (windowsize > 500) {
// do this
}
이것은 아주 잘 작동하지만, 저는 이와 같은 방법을 적용하고 싶지만, 다양한 숫자를 사용하고 싶습니다.그래서 저는 윈도우 크기가 500px에서 600px 사이라면 브라우저에 무언가를 하라고 말하고 싶습니다.이것이 효과가 없을 것이라는 것을 알지만, 제가 상상한 것은 다음과 같습니다.
if (windowsize > 500-600) {
// do this
}
자바스크립트 내에서 이것이 가능합니까?
테스트 여부windowsize
보다 큼500
이하600
둘 다 가치가 없다는 뜻500
또는600
그 자체는 그 조건이 진실이 되는 결과를 초래할 것입니다.
if (windowsize > 500 && windowsize < 600) {
// ...
}
잠시 시간이 있었으므로, 이미 답변을 수락하셨지만, 다음과 같이 기여할 것으로 생각했습니다.
Number.prototype.between = function(a, b) {
var min = Math.min.apply(Math, [a, b]),
max = Math.max.apply(Math, [a, b]);
return this > min && this < max;
};
var windowSize = 550;
console.log(windowSize.between(500, 600));
JS 피들 데모.
또는 종단점을 포함하여 정의된 범위에 있는 번호를 확인하는 옵션을 선택할 수 있습니다.
Number.prototype.between = function(a, b, inclusive) {
var min = Math.min.apply(Math, [a, b]),
max = Math.max.apply(Math, [a, b]);
return inclusive ? this >= min && this <= max : this > min && this < max;
};
var windowSize = 500;
console.log(windowSize.between(500, 603, true));
JS 피들 데모.
코멘트에 명시된 바와 같이, 위에 작은 수정 사항을 추가하기 위해 편집되었습니다.
…
Function.prototype.apply()
느려요!논쟁의 양이 정해져 있을 때 그것을 부르는 것은 무의미합니다.
의 사용을 제거할 가치가 있었습니다.Function.prototype.apply()
이는 위의 방법의 수정된 버전을 산출합니다. 첫째, '수정' 옵션이 없습니다.
Number.prototype.between = function(a, b) {
var min = Math.min(a, b),
max = Math.max(a, b);
return this > min && this < max;
};
var windowSize = 550;
console.log(windowSize.between(500, 600));
JS 피들 데모.
또한 '포함' 옵션을 사용하면 다음과 같습니다.
Number.prototype.between = function(a, b, inclusive) {
var min = Math.min(a, b),
max = Math.max(a, b);
return inclusive ? this >= min && this <= max : this > min && this < max;
}
var windowSize = 500;
console.log(windowSize.between(500, 603, true));
JS 피들 데모.
참조:
변수를 내부에 배치하여 코드가 내 변수가 범위 값 사이에 있는지 확인하고 있다는 추가 힌트를 주는 것을 선호합니다.
if (500 < size && size < 600) { doStuff(); }
오래된 질문이지만 저 같은 사람에게 유용할 수도 있습니다.
lodash
가지다_.inRange()
함수 https://lodash.com/docs/4.17.4#inRange
예:
_.inRange(3, 2, 4);
// => true
이 방법은 다음을 활용합니다.Lodash
유틸리티 라이브러리. 설치된 Lodash 버전에 액세스해야 합니다.
간단하게 할 수 있습니다.
if (windowsize > 500 && windowsize < 600) {
//your logic
}
또는 깨끗한 코드를 원한다면 당신은 당신의 메인 js 파일에 당신만의 기능을 쓸 수 있습니다.
Number.prototype.between = function(a, b) {
var min = Math.min.apply(Math, [a, b]),
max = Math.max.apply(Math, [a, b]);
return this > min && this < max;
};
그러면 이렇게 부를 수 있습니다.
if(windowsize.between(500, 600)){
//your logic
}
허용된 답변이 있다는 것을 알고 있지만 특정 시나리오에서 유용한 몇 가지 방법을 제공하고 싶습니다.우리가 확인하고 싶다면,n
사이에x
그리고.y
우리는 할 수 있습니다.
x <= n && n <= y
(x - n) * (y - n) <= 0
두 번째는 스왑해도 동일한 결과를 얻으려고 할 때 매우 유용합니다.x
그리고.y
.
을 사수있다니습용에 있는 할 수 .if
대 건 조 글 건 조
if (windowsize > 500-600) {
// do this
}
왜냐하면 이것은 논리적으로 말이 안되기 때문입니다. 자바스크립트는 당신의 if 조건을 읽을 것입니다.
windowSize > -100
은 그은계기때문에를 계산하기 때문입니다.500-600
-100
당신은 야합다니해를 사용해야 .&&
, 예를 들어, 이렇게 에는, 두 경 엄 위 다 같 보 것 일 이 입 니 다 과 음 들 어 예 를 해 우 를 기 하 격 하 확 게 인 니 ▁for ▁both 것 다 입 ▁strict ▁cases ▁which ▁checking ▁for ▁example ▁this
if( windowSize > 500 && windowSize < 600 ){
// Then doo something
}
가능한 가장 짧은 방법은 다음과 같습니다.
if (Math.abs(v-550)<50) console.log('short')
if ((v-500)*(v-600)<0) console.log('short')
매개 변수화:
if (Math.abs(v-max+v-min)<max+min) console.log('short')
if ((v-min)*(v-max)<0) console.log('short')
첫번째 것이 어떻게 작동하는지 이해가 안된다면 양쪽을 2로 나눌 수 있습니다;)
이것은 일반적인 방법입니다, 당신은 어디에서나 사용할 수 있습니다.
const isBetween = (num1,num2,value) => value > num1 && value < num2
부트스트랩 모달 값을 표시하고 숨기기 위해 jQuery의 일부를 구현했습니다.사용자 텍스트 상자 항목의 값 범위에 따라 다른 필드가 표시됩니다.
$(document).ready(function () {
jQuery.noConflict();
var Ammount = document.getElementById('Ammount');
$("#addtocart").click(function () {
if ($(Ammount).val() >= 250 && $(Ammount).val() <= 499) {
{
$('#myModal').modal();
$("#myModalLabelbronze").show();
$("#myModalLabelsilver").hide();
$("#myModalLabelgold").hide();
$("#myModalPbronze").show();
$("#myModalPSilver").hide();
$("#myModalPGold").hide();
}
}
});
데이비드가 대답하는 것처럼 하지만 나는 a나 b 둘 중 하나를 포함해야 했습니다. 그래서 나의 솔:
export const between = (num: number, a: number, b: number, inclusiveA = true, inclusiveB = true): boolean => {
if (a > b) [a, b, inclusiveA, inclusiveB] = [b, a, inclusiveB, inclusiveA];
if (a == b && (inclusiveA || inclusiveB)) [inclusiveA, inclusiveB] = [true, true];
return (inclusiveA ? num >= a : num > a) && (inclusiveB ? num <= b : num < b);
};
if (require.main === module) {
console.log(between(12, 15, 10)); //true
console.log(between(15, 15, 10)); //true
console.log(between(15, 10, 15)); //true
console.log(between(10, 10, 15, false)); //false
console.log(between(15, 10, 10, true, false)); //false
//edge case: if a==b then enough that either of the edges is inclusive
console.log(between(10, 10, 10, true, false)); //true
}
자바스크립트가 아닌 타이프스크립트도 있습니다.
function handleBetween(number, calc) {
let [a, b] = calc;
let min = Math.min(a, b), max = Math.max(a, b);
return number > min && number < max;
}
if(510 >500 && 510 <600){
console.log(`510 >500 && 510 <600 is true`)
}
if(610 >500 && 610 <600){
// false
console.log(`610 >500 && 610 <600 is true`)
} else console.log(`610 >500 && 610 <600 is false`)
console.log(handleBetween(510, [500, 600])); // true
console.log(handleBetween(610, [500, 600])); // false
언급URL : https://stackoverflow.com/questions/14718561/how-to-check-if-a-number-is-between-two-values
'programing' 카테고리의 다른 글
왼쪽 결합 위치 절 (0) | 2023.08.20 |
---|---|
파이썬 심플PHP를 사용하는 HTTPS 서버 (0) | 2023.08.20 |
소켓 listen() backlog 매개 변수의 값을 결정하는 방법은 무엇입니까? (0) | 2023.08.20 |
12c에서 utl_http &wallet 사용: 인증서 유효성 검사 실패 (0) | 2023.08.20 |
Angular2에서 다중 경로 매개변수 전달 (0) | 2023.08.20 |