希望这是一个可以在这里问的好问题...
因此,我得到了一些帮助,以创建一个查找模式的函数(数组中出现次数最多的数字)。但是现在我需要一点帮助来理解它...
(我是编程的新手)
数据保存着“信息”,在另一个文件中包含多个数组。
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/