[英]what is the easiest way to finding a match between values
我試圖找到兩個對象值之間的matching value
值。 我可以每次迭代數組來獲取它。
但我正在尋找一些最簡單的方法......任何人都能幫助我嗎?
這是我要找的:
let values = [
{
"handlingFee": "0.65",
"min": "0",
"max": "50000"
},
{
"handlingFee": "0.60",
"min": "50000",
"max": "150000"
},
{
"handlingFee": "0.55",
"min": "150000",
"max": "999999999"
}
];
var findHandlingFee = function(){
return values[0].handlingFee;
}
findHandlingFee(3000); //handlingFee": "0.65
findHandlingFee(5010); //handlingFee": "0.60"
findHandlingFee(300000); //"handlingFee": "0.55"
您可以使用find
方法接受回調函數作為參數。
let values = [ { "handlingFee": "0.65", "min": "0", "max": "50000" }, { "handlingFee": "0.60", "min": "50000", "max": "150000" }, { "handlingFee": "0.55", "min": "150000", "max": "999999999" } ]; var findHandlingFee = function(value){ return values.find(function(item){ return item.min <= value && item.max >= value; }).handlingFee; } console.log(findHandlingFee(3000)); //handlingFee": "0.65 console.log(findHandlingFee(50010)); //handlingFee": "0.60" console.log(findHandlingFee(300000));
您可以使用array#filter方法。它將返回一個數組,但可以自定義返回條件
let values = [{ "handlingFee": "0.65", "min": "0", "max": "50000" }, { "handlingFee": "0.60", "min": "50000", "max": "150000" }, { "handlingFee": "0.55", "min": "150000", "max": "999999999" } ]; function findHandlingFee(val) { return values.filter(function(item) { // return that object where the val is between max and min value return +item.min <= val && +item.max >= val; }) } //[0] since filter return an array,getting only object in 0 index console.log(findHandlingFee(3000)[0].handlingFee);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.