【发布时间】:2021-06-21 18:12:15
【问题描述】:
正如标题所示,我在 HTML 页面上显示随机数组中每个整数的出现次数时遇到了一些问题。我希望让它显示“X 出现 N 次”或类似的东西,但是当我添加一个字符串时,它在控制台中显示为未定义,如果我只是单独放置这些值,则显示正确的值。我会证明我的意思:
function Display(id, content) { // this works fine just included for context
let element = document.getElementById(id);
element.innerHTML = content;
}
function GetOccurences(amt) { // here is where I have my issue
count = {};
arr.forEach(function(amt) {
count[amt] = count[amt] + 1 || 1
return count, amt;
});
console.log(count); // Displays correct date in console, though no room to insert dialogue
Display("occursId", count); //Displays undefined on HTML page
}
GetOccurences("test")
我做错了什么?在此先感谢您提供的所有帮助
【问题讨论】:
-
你为什么有
return count, amt;?forEach()不对回调函数的返回值做任何事情。另外,你不能在 JS 中返回多个值。 -
将对象传递给
Display()只会显示[Object object]。你应该传递一个字符串。 -
GetOccurrences()没有使用它的参数,因为您在forEach()回调函数中重用了变量amt。 -
如果您计算整数的出现次数,
GetOccurrences的test参数有什么意义? -
我没有做测试.. 我想有人编辑并添加了那个,尽管我不知道为什么。
标签: javascript html arrays function