मेरे पास एक पल था, इसलिए, हालांकि आप पहले से ही एक जवाब स्वीकार कर चुके हैं, मैंने सोचा कि मैं निम्नलिखित योगदान करूंगा:
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));
जेएस फिडेल डेमो ।
या, यदि आप एक नंबर की जांच करने का विकल्प रखना चाहते हैं, तो अंतिम बिंदुओं सहित परिभाषित सीमा में है :
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));
जेएस फिडेल डेमो ।
उपरोक्त में एक मामूली संशोधन जोड़ने का सुझाव दिया गया है, जो टिप्पणी में उल्लिखित है -
… 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));
जेएस फिडेल डेमो ।
और 'समावेशी' विकल्प के साथ:
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));
जेएस फिडेल डेमो ।
संदर्भ: