如何在JavaScript CLI问答游戏中从数组对象获取最高分并对比?
问题分析
原代码中遍历highscore数组的循环仅逐个赋值currenthq,循环结束后currenthq仅保留数组最后一个元素的信息,导致无法正确对比用户得分与所有高分中的最大值。
解决方案
以下提供三种高效实现方式:
方法1:使用Array.reduce()提取最高分
利用reduce遍历数组并计算最大值,是处理这类场景的常用方案:
// 替换原有的highscore循环部分 const highestScore = highscore.reduce((max, entry) => { return entry.score > max ? entry.score : max; }, 0); // 初始值设为0,兼容空数组场景 // 对比用户得分 if (score > highestScore) { console.log("Woohoo! You've beaten the high score. Send me a screenshot and I'll update it. "); } else { console.log("Thank You for playing! "); }
方法2:基础循环跟踪最高分
如果偏好基础循环写法,可在遍历过程中维护当前最高分:
let highestScore = 0; for (let i = 0; i < highscore.length; i++) { if (highscore[i].score > highestScore) { highestScore = highscore[i].score; } } // 对比得分 if (score > highestScore) { console.log("Woohoo! You've beaten the high score. Send me a screenshot and I'll update it. "); } else { console.log("Thank You for playing! "); }
方法3:结合Math.max()与Array.map()
通过map提取所有分数,再用Math.max取最大值:
const scores = highscore.map(entry => entry.score); const highestScore = Math.max(...scores); // 展开运算符传递所有分数 // 对比得分 if (score > highestScore) { console.log("Woohoo! You've beaten the high score. Send me a screenshot and I'll update it. "); } else { console.log("Thank You for playing! "); }
完整修正后代码
var readlineSync = require('readline-sync'); var userName = readlineSync.question("Hey there! Can you tell us your Name? " ) console.log("Welcome! " + userName + " let's play a game 'Do you know Manan?'") var score = 0; var highscore = [{ name: "Jay", score: 5, }, { name: "Sanan", score: 2, } ] function qna(question, answer){ var userAnswer = readlineSync.question(question); if (userAnswer.toUpperCase() === answer.toUpperCase()){ console.log("You're Right!"); score = score + 1; } else { console.log("You're Wrong!"); } console.log("Your score: " + score); } const questionOne = { question: "Who is my favorite superhero? ", answer: "thor", } const questionTwo = { question: "Which is my favorite Movie? ", answer: "la la land", } const questionThree = { question: "Which is my favorite food? ", answer: "pasta", } var quiz = [questionOne, questionTwo, questionThree] for (let i=0; i < quiz.length; i++){ var currentq = quiz[i]; qna(currentq.question, currentq.answer); } // 获取最高分 const highestScore = highscore.reduce((max, entry) => entry.score > max ? entry.score : max, 0); if (score > highestScore){ console.log("Woohoo! You've beaten the high score. Send me a screenshot and I'll update it. "); } else { console.log("Thank You for playing! "); }
内容的提问来源于stack exchange,提问作者Manan Khurrana
相关产品推荐
相关产品推荐

