简体   繁体   English

显示数组中文本的随机值

[英]Display random value of text from an array

I have the following: 我有以下内容:

var movie;

var myMovies = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter','Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter','Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

function generateMovies () {
  var movie = myMovies[Math.floor(Math.random() * myMovies.length)];
}


function displayMovie() {
  generateMovies();
  console.log(movie);
  $('body').text(movie);

  setTimeout(function(){
    displayMovie();
},1000);
}

displayMovie();

I would like to generate a different movie name and show them on the screen. 我想生成一个不同的电影名称并将其显示在屏幕上。 Seems to be straight forward but obviously not! 似乎直截了当,但显然不是! Seems like may variable is undefined. 好像may变量是未定义的。

Thanks! 谢谢!

Fiddle: https://jsfiddle.net/4ggwva4f/8/ 小提琴: https : //jsfiddle.net/4ggwva4f/8/

您在函数内部声明了变量movie,因此没有将值分配给全局变量。

Just remove var in your generateMovies function. 只需在generateMovies函数中删除var

function generateMovies () {
  movie = myMovies[Math.floor(Math.random() * myMovies.length)];
}

Basically, you're declaring movie first at the start of your script, then again within your generateMovies function, so movies is not being returned into your global scope. 基本上,您首先在脚本的开头声明movie ,然后在generateMovies函数中再次声明movie ,因此影片不会返回到全局范围中。

As the other guys mentioned, you have a scope problem. 正如其他人提到的那样,您遇到了范围问题。 Also, you don't really need the global movie variable, you could change your code to return the expected value like this: 另外,您实际上并不需要全局movie变量,可以更改代码以返回期望值,如下所示:

var myMovies = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter','Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter','Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

function generateMovies () {
  return myMovies[Math.floor(Math.random() * myMovies.length)];
}

function displayMovie() {
  var movie = generateMovies();
  console.log(movie);
  $('body').text(movie);

  setTimeout(function(){
    displayMovie();
},1000);
}

displayMovie();

Or if you don't really need to do the console.log just: $('body').text(generateMovies()) 或者,如果您真的不需要做console.log只需: $('body').text(generateMovies())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM