在这里你有一个解决方案:
RangeCheck = function(range) {
this.init(range);
};
RangeCheck.prototype = {
constructor: RangeCheck,
/**
* The range map.
*/
range: null,
init: function (range) {
this.range = range || {};
},
putRange: function(name, max) {
this.range[name] = max;
},
check: function(number) {
for (var key in this.range) {
if (this.range.hasOwnProperty(key)) {
if (number <= this.range[key]) {
return key;
}
}
}
return key;
}
};
像这样使用它:
var rangeCheck = new RangeCheck({ small : 25, medium : 80, large : 150 });
var message = "15: " + rangeCheck.check(15) + "\n"
+ "25: " + rangeCheck.check(25) + "\n"
+ "85: " + rangeCheck.check(85) + "\n"
+ "850: " + rangeCheck.check(850) + "\n";
alert(message);
rangeCheck.putRange("veryLarge", 300);
var message = "15: " + rangeCheck.check(15) + "\n"
+ "25: " + rangeCheck.check(25) + "\n"
+ "85: " + rangeCheck.check(85) + "\n"
+ "850: " + rangeCheck.check(850) + "\n";
alert(message);
和 jsFiddle:http: //jsfiddle.net/xKjt7/