You're going on a trip with some students and it's up to you to keep track of how much money each Student has. A student is defined like this:
class Student {
constructor(name, fives, tens, twenties) {
this.name = name;
this.fives = fives;
this.tens = tens;
this.twenties = twenties;
}
}
As you can tell, each Student has some fives, tens, and twenties. Your job is to return the name of the student with the most money. If every student has the same amount, then return "all".
Notes:
Each student will have a unique name
There will always be a clear winner: either one person has the most, or everyone has the same amount
If there is only one student, then that student has the most money
我试过这个:
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];
}
}
对我来说没有意义的是,当我
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
将所有总数收集到一个数组中。循环,然后在循环后对该数组进行排序-该逻辑有什么问题?最佳答案
工作解决方案:)
function mostMoney(students) {
let array = [];
if (students.length === 1) {
return students[0].name;
}
students.forEach((value, index) => {
let total = ((5 * value.fives) + (10 * value.tens) + (20 * value.twenties));
array.push([total, value.name]);
});
array = array.sort((a, b) => b[0] - a[0]);
if (array.every((el, i, array) => el[0] === array[0][0])) {
return 'all';
}
else {
return array[0][1];
}
}
实际上我的
.every
有问题- 我在做 (el)[0])
而不是 el[0]
,然后我也没有正确检查何时只有一名学生传入 mostMoney
.感谢大家阐明console.log 问题。 Codewars 是 console.logging 多次,因为正如你们所提到的,它正在运行多个测试。
关于javascript - 谁拥有最多的钱 - Codewars 挑战 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58885076/