慕尼黑8549860
我遇到了比较的问题。结果假设为 11,因为索引 11 的产品成本低于索引 18 的产品成本。但不知何故结果是 18 var scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53, 55, 61, 51, 44]; var costs = [.25, .27, .25, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25, .25, .25, .27, .25, .26, .29];//TOTAL, HIGHEST, INDEX OF THE HIGHESTfunction index(array,arrayCost){ var maximum=Math.max(...array); var arrayIndex=[]; for(var i=0;i<array.length;i++){ if(array[i]==maximum){ arrayIndex.push(i) } } var minimum=arrayCost[arrayIndex[0]];//0.22 for(var i=0;i<arrayIndex.length;i++){ if(arrayCost[arrayIndex[i]]<=minimum){//0.25>=0.22 minimum=arrayIndex[i]; } } return minimum;}
慕虎7371278
您的错误显示在评论中,但我会对其进行修改以使用单个循环:var scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53, 55, 61, 51, 44]; var costs = [.25, .27, .25, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25, .25, .25, .27, .25, .26, .29];function index(array, arrayCost) { var maxScore = Math.max(...array); var minCostIndex = null; for (var i = 0; i < arrayCost.length; i++) { if (array[i] != maxScore) { continue; } if (minCostIndex == null || arrayCost[i] < arrayCost[minCostIndex]) { minCostIndex = i; } } return minCostIndex;}console.log("res", index(scores, costs));如果你愿意,你甚至可以消除Math.max:var scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53, 55, 61, 51, 44]; var costs = [.25, .27, .25, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25, .25, .25, .27, .25, .26, .29];function index(array, arrayCost) { var maxScore = array[0]; var minCostIndex = 0; // start iteration at 1, since 0 is accounted for in the vars for (var i = 1; i < arrayCost.length; i++) { if (array[i] > maxScore) { maxScore = array[i]; minCostIndex = i; continue } if (array[i] == maxScore && arrayCost[i] < arrayCost[minCostIndex]) { minCostIndex = i; } } return minCostIndex;}console.log("res", index(scores, costs));