使用getElementById展示数组内容失败,寻求帮助
Hey there! Let's work through why your code isn't displaying the array elements like you want. I've noticed a couple of small issues that are causing the problem:
Your JavaScript runs before the HTML element exists
Browsers parse code from top to bottom. When your JS tries to grabdocument.getElementById("fruits"), that<h1>element hasn't been created yet—so it can't update its content. You need to move your JS code after the<h1>tag, or wrap it in an event that waits for the DOM to fully load.Typos in your array
You've got a typo:"applle"should be"apple"(extra 'l'). This won't break the code, but it'll show a misspelled fruit name!Array formatting for display
If you just assign the array directly toinnerHTML, it'll show up as a comma-separated string (likeapple,orange,grape). If you want a cleaner display, use thejoin()method to format it—for example, adding line breaks or spaces between items.
Here's a fixed version of your code that should work as expected:
<h1 id="fruits">fruit stall</h1> <script> let winter = ["apple","orange","grape"]; console.log(winter); // Use join to add line breaks between each fruit document.getElementById("fruits").innerHTML = winter.join("<br>"); </script>
If you prefer the fruits separated by commas with spaces, just change join("<br>") to join(", ") instead. That should get your fruit list showing up correctly!
备注:内容来源于stack exchange,提问作者Learner

