ちょっと時間があったので、あなたはすでに答えを受け入れていますが、私は次のように貢献したいと思いました:
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 フィドルのデモ。
または、数値がend-points を含む定義された範囲内にあるかどうかを確認するオプションが必要な場合:
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 フィドルのデモ。
参考文献: