希望这是一个可以在这里问的问题...... 因此,我在创建一个函数来查找众数(数组中出现次数最多的数字)时得到了一些帮助。但现在我需要一点帮助来理解它...... (我对编程完全陌生) 数据保存着“信息”,在另一个文件中包含多个数组。
let mode = function(data) {
data.sort(function(a, b) {
return a - b;
});
let mode = {},
highestOccurrence = 0,
modes = [];
data.forEach(function(element) {
if (mode[element] === undefined) {
mode[element] = 1;
} else {
mode[element]++;
}
if (mode[element] > highestOccurrence) {
modes = [element];
highestOccurrence = mode[element];
} else if (mode[element] === highestOccurrence) {
modes.push(element);
highestOccurrence = mode[element];
}
});
return modes;
};
所以首先我只是对函数进行排序,以便数字将以正确的顺序出现。但是有人能帮我理解这个函数的其余部分吗?
最佳答案
我添加了一些注释,我只能推断是您提供的代码。您可以为您的问题提供更多背景信息,例如您拥有的数据类型以及您想要实现的目标,也许还可以提供有用的示例。
let mode = function(data) {
data.sort(function(a, b) {
return a - b;
});
let mode = {},
highestOccurrence = 0,
modes = [];
// This loops through data array (It should be data here and not data1)
data.forEach(function(element) {
// Here you check if the mode object already have that element key,
// setting the first occurence or incrementing it
if (mode[element] === undefined) {
mode[element] = 1;
} else {
mode[element]++;
}
// After that it checks if that mode has the higher occurence
if (mode[element] > highestOccurrence) {
// If it has the higher occurence it sets the modes to an array with
// that element and the highestOccurrence value to that value
modes = [element];
highestOccurrence = mode[element];
} else if (mode[element] === highestOccurrence) {
// If it has the same number of occurences it just adds that mode to
// the modes to be returned
modes.push(element);
highestOccurrence = mode[element];
}
});
return modes;
};
希望这对你有帮助
关于javascript - 了解查找众数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39570066/