У меня есть массив объектов, где нужно выполнить итерацию, чтобы найти и вернуть соответствующее значение.
function getCost(val) {
let arr = JSON.parse('[ { "hours": 1, "cost": 100 }, { "hours": 2, "cost": 50 }, { "hours": 3, "cost": 20 }, { "hours": 4, "cost": 10 }, { "hours": 5, "cost": 5 } ]')
for (var i = 0; i < arr.length; i++) {
var item = arr[i]
let hours = parseInt(item['hours'], 10)
if (hours == val) {
return item['cost']
}
/*this condition not working*/
if (hours > val) {
alert('exceed') //this not called at all
return arr[arr.length - 1]['cost']
}
}
}
alert(getCost(4)) /*this works*/
alert(getCost(8)) /*this not work, give undefined*/
Но почему, когда значение val больше значения сравнения, оно не работает.hours > val
просто не работает.Любая ошибка, которую я сделал?