简体   繁体   English

奇怪的javascript循环行为

[英]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. 但是为什么当val条件超过比较值时,它不起作用。 The hours > val simply doesn't work. hours > val根本不起作用。 Any mistake I made? 我犯了什么错误?

The behavior is expected because there is no condition to satisfy your "not working" if block. 行为是预期的,因为没有条件来满足你的“不工作” if块。 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)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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