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

网站加载随机事实功能失效,提示数组不是构造函数错误

解决数组不是构造函数的错误及随机事实功能实现

问题分析

你代码里的核心错误是数组创建语法错误:使用了new Array[],正确的Array构造函数调用应该用圆括号(),或者更简洁的数组字面量语法[]。另外还有两个小问题需要优化:

  • 随机数范围不对,你的数组有4个元素,但Math.floor(Math.random() * 3)只能生成0-2的索引,会漏掉最后一个元素
  • script标签放在了p标签内部,可能导致DOM元素获取失败

修正后的代码

<p id="sciencefact"></p>

<script>
  // 用数组字面量创建数组(更推荐的写法)
  const facts = [
    "Dead skin cells are commonly found in household dust",
    "The bumblebee bat is the world’s smallest mammal, weighing .05-.07 ounces",
    "There is parts of Africa in all four hemispheres",
    "The Phillipines is made of 7,641 islands"
  ];
  // 用数组长度计算随机索引,适配数组元素数量变化
  const factNumber = Math.floor(Math.random() * facts.length);
  console.log(factNumber);
  // 给p元素设置文本内容
  document.getElementById("sciencefact").innerText = facts[factNumber];
</script>

关键修正点

  • 把new Array[]改成[](数组字面量),如果一定要用构造函数,应写成new Array("元素1", "元素2", ...),但字面量写法更简洁直观
  • 随机数计算改为Math.random() * facts.length,不管数组里有多少条事实,都能随机取到任意一条
  • 把script标签移到p标签外面,确保执行脚本时p元素已被浏览器解析,能正常获取DOM节点

内容的提问来源于stack exchange,提问作者madman12

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:25:21