React JS中获取数组最高投票数出现NaN问题的解决咨询
修复React中获取最高投票数的问题
问题原因
你的votes是纯数字数组(初始通过Array(anecdotes.length).fill(0)创建),每个元素都是数字值,而非带vote属性的对象。但你使用了votes.map(function(o) { return o.vote ; }),这会把每个数字转为undefined,Math.max处理包含undefined的数组自然返回NaN。
修复方案
1. 正确获取最高投票数
直接对votes数组使用Math.max即可,无需额外的map操作:
// 扩展运算符写法(更直观) const highestVoteCount = Math.max(...votes); // 或者apply写法 const highestVoteCount = Math.max.apply(Math, votes);
2. 优化:显示得票最高的轶事
如果要展示对应的轶事内容,需要先找到最高票数的索引,再匹配对应的轶事文本:
// 找到最高票数的首个索引(若有并列最高,取第一个) const highestVoteIndex = votes.indexOf(highestVoteCount); // 对应轶事内容 const topAnecdote = anecdotes[highestVoteIndex];
完整修改后的App代码
const App = () => { const handleClick2 = () => { setSelected(Math.floor(Math.random()*anecdotes.length)) } const handleVotes = () => { setVotes((votes) => votes.map((vote, index) => index === selected ? vote + 1 : vote) ) } const anecdotes = [ 'If it hurts, do it more often.', 'Adding manpower to a late software project makes it later!', 'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.', ] const [selected, setSelected] = useState(0) const [votes, setVotes] = useState(() => Array(anecdotes.length).fill(0)) // 修复后的最高票数获取 const highestVoteCount = Math.max(...votes); // 获取得票最高的轶事 const highestVoteIndex = votes.indexOf(highestVoteCount); const topAnecdote = anecdotes[highestVoteIndex]; return ( <div style={inlineParagraph}> <h1>Anecdote of the day</h1> { anecdotes[selected] } <div style={inlineButton} > <Button handleClick={handleClick2} text="next anecdotes" setSelected={setSelected} /> <Button handleClick={handleVotes} text="vote" setSelected={setSelected}/> : {votes[selected]} </div> <h1>Anecdote with the most votes</h1> {/* 显示轶事内容及对应票数 */} <p>{topAnecdote}</p> <p>Votes: {highestVoteCount}</p> </div> ) } export default App
补充说明
- 若数组为空,
Math.max会返回-Infinity,但你的初始votes是填充了0的数组,不会出现这种情况。 - 若需处理多个并列最高的轶事,可使用
filter找到所有对应索引,再遍历展示。
内容的提问来源于stack exchange,提问作者Jabri Juhinin
相关产品推荐
相关产品推荐

