I'm currently working on a JavaScript project involving arrays and forEach loops, and I'm facing an issue that I can't seem to resolve. I want to display the contents of an array with a twist: I'd like to show the string "undefined" for any empty indices in the array. However, despite trying various approaches, I still can't achieve the desired result.
Here's the code I'm using:
const fruits = ["banana", "apple", "watermelom", "grapes"];
fruits[7] = "Lemon";
let text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value, index) {
if (index in fruits) {
text += "<li>" + value + "</li>";
} else {
text += "<li>undefined</li>";
}
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>
Unfortunately, this code isn't achieving the result I want, and I'm still not seeing "undefined" displayed for the empty indices. Is there something I'm missing or misunderstanding about using the forEach loop in this context? Any insights or alternative solutions would be greatly appreciated. Thank you in advance for your assistance!