了解功能,找到模式
Understanding function to find mode
希望这是一个可以问的问题…所以我得到了一点帮助,创建了一个函数来查找模式(在数组中出现次数最多的数字)。但现在我需要一点帮助来理解它……(我是一个编程新手)数据是保存"信息",包含多个数组在另一个文件。
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;
};
希望这对你有帮助
相关文章:
- 添加文字和评论功能更新Div
- Javascript,访问一个主要对象模块模式中的每个对象
- JavaScript打印功能使日历停止工作
- 是否有任何snippet或jQuery插件可以列出easylist.txt模式匹配的DOM中的所有元素
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 在单模式中断功能中使用Ajax渲染部分
- 为什么Chrome在“严格模式”下使用块内的功能时仍然保持沉默
- Twitter引导模式的黄瓜功能
- 如何在 Crockford 的新构造函数模式中共享“构造函数”功能
- HTML Javascript 模式弹出窗口,具有自动关闭功能
- 允许向对象添加和删除功能的设计模式
- 如何在正文加载时以全屏模式(F11 功能)打开网页
- jQuery:如果内容与正则表达式模式匹配,则执行此功能
- Twitter引导模式远程功能不能正常工作
- 如何在引导模式中添加功能- Laravel
- 如何在一个引导模式从另一个模式打开滚动功能
- 流星错误:无此功能:仅在生产模式下
- Javascript继承:用模块模式和$.extend覆盖功能
- 了解功能,找到模式
- 了解一个基本的模块模式的私有和公共功能