显示JS数组中的事件,在控制台中返回正确,但在HTML上未定义



正如标题所示,我在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")

我做错了什么?提前感谢的任何帮助

getOccurrences()应将arr作为参数,而不是amt

在调用Display()之前,您需要将返回的值转换为包含格式化结果的字符串。

function Display(id, content) {
let element = document.getElementById(id);
element.innerHTML = content;
}
function GetOccurences(arr) {
const count = {};
arr.forEach(function(num) {
count[num] = count[num] + 1 || 1
});
const formatted = Object.entries(count).map(([num, amt]) => 
`${num} appears ${amt} times`).join('<br>');
Display("occursId", formatted);
}
GetOccurences([1, 2, 4, 2, 3, 8, 1, 2, 5])
<div id="occursId"></div>

相关内容

最新更新