簡體   English   中英

奇怪的javascript循環行為

[英]Strange javascript looping behavior

我有一個對象數組,需要迭代才能找到並返回相應的值。

 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根本不起作用。 我犯了什么錯誤?

行為是預期的,因為沒有條件來滿足你的“不工作” if塊。 您可以檢查最后一個索引

 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