Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 尝试返回具有最高值对象的父数组的索引_Javascript_Arrays - Fatal编程技术网

Javascript 尝试返回具有最高值对象的父数组的索引

Javascript 尝试返回具有最高值对象的父数组的索引,javascript,arrays,Javascript,Arrays,我正在学习我的JavaScript课程,并重温ES6中的所有编码练习 我有一系列的团队。数组中的每个团队都是一个对象。我想比较它们并返回赢家,然而,我的目标是以一种可伸缩的方式来实现这一点(如果我想在将来添加更多团队的话) 下面是我到目前为止的代码。我希望它能够评估任意数量的数组。我面临的问题是,它将只计算前两个数组 class Team { constructor(teamName, scores) { this.teamName = teamName, this.sc

我正在学习我的JavaScript课程,并重温ES6中的所有编码练习

我有一系列的团队。数组中的每个团队都是一个对象。我想比较它们并返回赢家,然而,我的目标是以一种可伸缩的方式来实现这一点(如果我想在将来添加更多团队的话)

下面是我到目前为止的代码。我希望它能够评估任意数量的数组。我面临的问题是,它将只计算前两个数组

class Team {
    constructor(teamName, scores) {
    this.teamName = teamName,
    this.scores = scores;
    this.avgScore = Math.floor(this.scores.reduce((prev, cur) => (prev + cur) / this.scores.length));
    }
}
 
// Generate some random scores
randomNumber = () => parseInt(Math.random() * 250);
randomScore = () => [randomNumber(), randomNumber(), randomNumber()];
 
// Create the teams
let teams = [
    new Team('Team John', randomScore()),
    new Team('Team Mike', randomScore()),
    new Team('Team Mary', randomScore())
]

 
// so I can debug
for (el of teams) {
    console.log(`${el.teamName}: ${el.avgScore}`)
}

// attempt to make this scalable
let winner = 0;
calcWinner = () => teams.reduce((prev, cur, index) => cur.avgScore > prev.avgScore ? winner = index : winner = winner);
calcWinner();
 
// More debug
console.log(winner);
 
// Log result to the console
console.log(`The team with the highest average is ${teams[winner].teamName}, with a score of ${teams[winner].avgScore}`)

您没有在reduce方法中设置并返回prev(最高分数)。首先,在reduce方法中将prev初始化为零。如果cur.avgScore大于prev,则将最高分数放入prev。这是数组的语法。reduce: array.reduce(函数(total、currentValue、currentIndex、arr)、initialValue)

班级团队{
构造函数(团队名称、分数){
(this.teamName=teamName),(this.scores=scores);
this.avgScore=Math.floor(
this.scores.reduce((prev,cur)=>prev+cur)/this.scores.length
);
}
}
//生成一些随机分数
randomNumber=()=>parseInt(Math.random()*250);
randomScore=()=>[randomNumber(),randomNumber(),randomNumber()];
//创建团队
让团队=[
新团队(“约翰团队”,randomScore()),
新团队(“迈克团队”,randomScore()),
新团队(“玛丽团队”,randomScore()),
];
//这样我就可以调试了
对于(团队的el){
log(`${el.teamName}:${el.avgScore}`);
}
//尝试使其可扩展
让胜利者=0;
calcWinner=()=>
团队。减少((上一个、当前、索引)=>{
如果(当前avgScore>prev){
赢家=指数;
prev=cur.avgScore;
}
返回上一个;
}, 0);
calcWinner();
//更多调试
console.log(获胜者);
//将结果记录到控制台
console.log(
`平均得分最高的团队为${teams[winner].teamName},得分为${teams[winner].avgScore}`

);这里有两件事你搞错了:

  • 平均计算:
  • 这应该是筛选最高平均水平团队的代码:

  • 一个附带问题:你没有正确计算平均值。它应该是
    this.avgScore=Math.floor(this.scores.reduce((prev,cur)=>(prev+cur))/this.scores.length)
    (我将分区移出了
    reduce
    调用。)@ScottSauyet谢谢!我永远不会发现这解决了它!谢谢你的解释。看起来我需要进一步阅读reduce方法。非常感谢。很高兴看到我使用reduce方法的替代方法。我曾考虑过forEach,但无法理解其中的逻辑。但我很高兴地说,我明白这是为什么:)
    this.avgScore = Math.floor(this.scores.reduce((total, current) => (total + current)) / this.scores.length);
    
    let winner = team[0];
    teams.forEach(team => {
      if(team.avgScore > winner.avgScore ) {
        winner = team; 
      }
    });
    
    colsole.log(`Team name: ${winner.teamName} , Average Score: ${winner.avgScore}`)