页面加载时随机生成变量

时间:2019-05-12 02:51:29

标签: javascript html arrays

我正在尝试使用JavaScript创建子手游戏,但是,我遇到了一个问题,即试图让页面加载时随机生成的名称。任何建议将不胜感激!

请查看代码。

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
  <p id='movie-title'></p>
  <footer>
  </footer>
</body>
</html>
var movieTitles = [
  "Halloween",
  "Suspiria",
  "Audition",
  "Hereditary",
  "The Beyond",
  "The Evil Dead",
  "The Blair Witch Project"
];

function randomMovieTitle(movie) {
  return "Movie Title:"+ " " + movie;
}
document.getElementById("movie-title").innerHTML = randomMovieTitle("Halloween");

我也尝试过

moviesToGuess = movieTitles[Math.floor(Math.random() * movieTitles.length)];

“万圣节”所在的位置

document.getElementById("movie-title").innerHTML = randomMovieTitle("Halloween");

但是我无法随机生成它,我一直在尝试我们

document.getElementById("movie-title").onload = function() {randomMovieTitle()};

以加载页面。

要使页面在页面加载时随机生成其中一部电影标题。

1 个答案:

答案 0 :(得分:0)

只需在函数调用中使用Math.random

var movieTitles = [
  "Halloween",
  "Suspiria",
  "Audition",
  "Hereditary",
  "The Beyond",
  "The Evil Dead",
  "The Blair Witch Project"
];

function randomMovieTitle(movie) {
  return "Movie Title: " + movie;
}
document.getElementById("movie-title").innerHTML = randomMovieTitle(movieTitles[Math.floor(Math.random() * movieTitles.length)]);
<p id='movie-title'></p>

按几次Run code snippet即可查看其运行情况。