let new_arr = [
{
"quantity": 3,
"discount": 0.99
}, {
"quantity": 4,
"discount": 0.95
}, {
"quantity": 6,
"discount": 0.90
}, {
"quantity": 10,
"discount": 0.88
}
]
/**
* @method
* @author gedesiwen
* @param {array} arr 需要查找的数组
* @param {number} num 目标数值,查找的是与这个数值最接近的
* @return {object} 获取数组中<=目标数值的元素
* @desc 获取数组中<=目标数值的元素
*/
function findCloseNum(arr, num) {
// 过滤出小于等于目标值的元素
let new_arr = arr.filter(item => {
return item.quantity <= num;
});
// 获取到new_arr中最大值
let maxItem = Math.max.apply(Math, new_arr.map(item => { return item.quantity }));
// 找到符合条件项
let checkedItem = arr.find(item => item.quantity == maxItem);
// 返回结果
return checkedItem || {};
}
/**
折扣规则获取到了,根据取到折扣取计算价格就好计算了
*/
console.log(1, findCloseNum(new_arr, 1));
console.log(2, findCloseNum(new_arr, 2));
console.log(3, findCloseNum(new_arr, 3));
console.log(4, findCloseNum(new_arr, 4));
console.log(5, findCloseNum(new_arr, 5));
console.log(6, findCloseNum(new_arr, 6));
console.log(7, findCloseNum(new_arr, 7));
console.log(8, findCloseNum(new_arr, 8));
console.log(9, findCloseNum(new_arr, 9));
console.log(10, findCloseNum(new_arr, 10));
console.log(100, findCloseNum(new_arr, 100));
结果
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…