【发布时间】:2019-11-15 21:42:09
【问题描述】:
您要和一些学生一起去旅行,您需要跟踪每个学生有多少钱。学生的定义如下:
class Student {
constructor(name, fives, tens, twenties) {
this.name = name;
this.fives = fives;
this.tens = tens;
this.twenties = twenties;
}
}
如您所知,每个学生都有一些 5、10 和 20。你的工作是返回钱最多的学生的名字。如果每个学生的数量相同,则返回“all”。
注意事项:
每个学生都有一个唯一的名字
总会有一个明显的赢家:要么一个人拥有最多,要么每个人拥有相同的数量
如果只有一个学生,那么那个学生的钱最多
我试过了:
function mostMoney(students) {
//get array of totals
let array = [];
students.forEach((value, index) => {
let total = ((5 * value.fives) + (10 * value.tens) + (20 * value.twenties));
array.push([total, value.name]);
});
//sort array of totals
array = array.sort((a, b) => b[0] - a[0]);
console.log('array****', array);
//check if all totals are equal - if they are, return 'all'
if (array.every((el, i, array) => (el)[0]) === array[0][0]) {
return 'all';
}
else {
return array[0][1];
}
}
对我来说没有意义的是,当我在 codewars 中 console.log('array****', array); 时,它看起来像:
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'David' ] ]
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'Cameron' ],
[ 30, 'Geoff' ],
[ 30, 'David' ] ]
array**** [ [ 40, 'Andy' ] ]
array**** [ [ 40, 'Stephen' ] ]
array**** [ [ 30, 'Cameron' ], [ 30, 'Geoff' ] ]
为什么会这样?我认为排序后,我的console.log('array***', array) 应该是这样的:
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'Cameron' ],
[ 30, 'Geoff' ],
[ 30, 'David' ] ]
当我最初console.log(students) 时,它看起来像一个数组:
[ Student { name: 'Andy', fives: 0, tens: 0, twenties: 2 },
Student { name: 'Stephen', fives: 0, tens: 4, twenties: 0 },
Student { name: 'Eric', fives: 8, tens: 1, twenties: 0 },
Student { name: 'David', fives: 2, tens: 0, twenties: 1 },
Student { name: 'Phil', fives: 0, tens: 2, twenties: 1 } ]
所以我尝试使用 forEach 循环将所有总数收集到一个数组中,然后在循环后对该数组进行排序 - 这个逻辑有什么问题?
【问题讨论】:
-
你的意思是你有多个控制台日志?
-
它看起来是这样,即使我在我的代码中只做一个 console.log:i.imgur.com/mFRlI3O.png
-
可能您的
mostMoney函数在您的测试中被多次调用?因此有多个控制台日志? -
代码正在针对一系列测试运行,因此控制台将记录多个数据集。
-
@c_ogoo 哦,好吧 - 这有助于消除一些混乱。那么问题仍然只是我的
.every(),我假设 - 当所有值都相同时,它不会返回 true。
标签: javascript arrays class instance