我有一个数组
[" 1–4 ": " $10.00 ", " 5–24 ": " $7.20 ", " 25–49 ": " $6.00 ", " 50+ ": " $5.80 "]
我需要检查来自此数组的输入值,以获得正确的价格来计算总价。
像这样,
$('.input-box').change(function(){
var num = $(this).val();
if (isInteger(num) ) {
}
});
我对JavaScript的选择是什么?
答案 0 :(得分:1)
根据您的评论,您似乎有一个与不同范围相关联的价格列表,并且您想要检查用户输入的值的价格(该值落在的范围内)。
如果是这种情况,你可以这样做:
var ranges = {" 1-4 ": " $10.00 ", " 5-24 ": " $7.20 ", " 25-49 ": " $6.00 ", " 50+ ": " $5.80 "}
$("#input-box").change(function(){
var val = $(this).val();
var price = Object.keys(ranges).reduce((a, c) => {
var s = c.trim();
if(/\d+\-\d+/.test(s)){
var range = s.split("-");
if(val >= parseInt(range[0]) && val <= parseInt(range[1])){
a = ranges[c];
}
}else{
s = s.replace(/\D/g, "");
if(val >= s){
a = ranges[c];
}
}
return a;
},0);
$("#price").text(price);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input-box" type="number">
<div>Price <span id="price"></span></div>
&#13;