首页 > 解决方案 > 从 JavaScript 数组中获取随机值(单击按钮)

问题描述

let text = ["hello", "world", "where", "list", "tes", "new"];
const btn = document.querySelector(".button");

btn.addEventListener("click", random);
const randomText = Math.floor(Math.random() * text.length);

function random() {
  const pText = document.querySelector(".p-text");
  const textRandom = (pText.innerHTML = `${text[randomText]}`);
}

嗨,伙计们,你能帮帮我吗?单击按钮时如何仍然获得随机结果?

标签: javascriptarraysfunction

解决方案


function random() {
  const pText = document.querySelector(".p-text");
  // move your randomText into function, so that it will have new value when the function is called.
  const randomText = Math.floor(Math.random() * text.length);
  const textRandom = (pText.innerHTML = `${text[randomText]}`);
}

推荐阅读