对象内两个方法出现无限循环,calcAvg无返回、checkWinner无输出
问题根因分析
- 两个方法的
for循环终止条件逻辑完全错误:你把「判断轮次是否存在」的表达式直接放在了和i比较的位置,JS会自动把布尔值/数组隐式转换为数值参与比较,最终导致循环一次都不会执行,自然没有输出。calcAvg里的i < (this.koalas["round" + i] && this.dolphins["round" + i]):当i=1时,右边返回的是轮次数组,1 < 数组的比较结果为false,循环直接终止,d和k始终是undefinedcheckWinner里的i < (this.koalas["round" + i].length && i < this.dolphins["round" + i].length):右边表达式返回的是布尔值,和i比较结果同样为false,循环完全不执行
修复后的完整代码
const team = { koalas: { round1: [65, 54, 49], round2: [23, 34, 27] }, dolphins: { round1: [64, 23, 71], round2: [85, 54, 41] }, calcAvg: function () { let d, k; // 修正循环条件:只要当前轮次同时存在就继续执行 for (let i = 1; this.koalas["round" + i] && this.dolphins["round" + i]; i++) { k = this.koalas["AvgRound" + i] = this.koalas["round" + i].reduce((a, b) => a + b) / this.koalas["round" + i].length; d = this.dolphins["AvgRound" + i] = this.dolphins["round" + i].reduce((a, b) => a + b) / this.dolphins["round" + i].length; console.log(`第${i}轮平均分:海豚队${d.toFixed(2)},考拉队${k.toFixed(2)}`); } return [d, k]; }, checkWinner: function () { // 修正循环条件:和calcAvg保持一致,只要轮次存在就判断胜负 for (let i = 1; this.koalas["round" + i] && this.dolphins["round" + i]; i++) { const koalaAvg = this.koalas["AvgRound" + i]; const dolphinAvg = this.dolphins["AvgRound" + i]; if (koalaAvg >= dolphinAvg * 2) { console.log(`第${i}轮:考拉队获胜!`); } else if (dolphinAvg >= koalaAvg * 2) { console.log(`第${i}轮:海豚队获胜!`); } else { console.log(`第${i}轮:无人获胜,获胜要求一方得分至少为另一方的两倍`); } } } } team.calcAvg(); team.checkWinner();
运行输出示例
第1轮平均分:海豚队52.67,考拉队56.00 第2轮平均分:海豚队60.00,考拉队28.00 第1轮:无人获胜,获胜要求一方得分至少为另一方的两倍 第2轮:海豚队获胜!
内容的提问来源于stack exchange,提问作者chessplayer
相关产品推荐
相关产品推荐

