简体   繁体   中英

Showing occurences in JS array, returns correct in console but undefined on HTML?

So as the title indicates, I'm having some issues displaying on an HTML page the amount of occurences of each integer in a randomized array. I'm hoping to get it display "X appears N times" or something along that sort, but when I add a string it appears as undefined in the console as well when the correct value shows if I just put the values alone. I'll demonstrate what I mean:

 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")

What am I doing incorrectly? Thanks in advance for any and all help

getOccurrences() should take arr as a parameter, not amt .

Before calling Display() , you need to convert the returned value to a string that contains your formatted results.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM