You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用getElementById展示数组内容失败,寻求帮助

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 grab document.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 to innerHTML, it'll show up as a comma-separated string (like apple,orange,grape). If you want a cleaner display, use the join() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 15:13:01