简体   繁体   中英

Strange javascript looping behavior

I have an array of objects, where need to iterate to find and return the corresponding value.

 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*/ 

But why when the val condition more then the compare value, it not working. The hours > val simply doesn't work. Any mistake I made?

The behavior is expected because there is no condition to satisfy your "not working" if block. You could check on the last index like this instead

 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'] } /*check if it is already the last iteration of the loop*/ if(i==arr.length-1){ alert('exceed') return arr[arr.length - 1]['cost'] } } } alert(getCost(4)) alert(getCost(8)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM