在多个地方使用相同的随机数(JavaScript) [英] Using the same random number in multiple places (JavaScript)

查看:77
本文介绍了在多个地方使用相同的随机数(JavaScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个随机的引用生成器,它应该随着引用它的人给你一个随机引号,但是我创建了两个单独的数组,因为它可以更容易地编辑稍后的页面。第一个数组有引号本身,第二个数组有名称的人。我想生成一个随机数,然后用它作为我的两个数组的索引,从而得到一个随机引用和相应的人说出来。



第一件事我试过是这样的:

pre $ var $ random $ index $ function $(
return Math.floor(Math.random() * quotes.length);
};

button.addEventListener(click,function(){
quoteBox.textContent =''+ quotes [randomIndex()] + people [randomIndex()] +''';
});

但是,这给了我两个不同的随机数(因为我调用函数两次,我想) 。然后我尝试将随机数设置为一个变量并将其用作索引,但除非刷新页面,并且我希望它通过单击按钮更改,否则不会更改。尝试调用 randomIndex em>内部您的点击处理程序。

  button.addEventListener(click,function(){
var random = randomIndex();
quoteBox.textContent =''+ quotes [random] + people [random] +''';
});

这会在每次点击处理程序运行时分配一个新的索引,但会使用相同的索引来访问都是引号人物


I'm creating a random quote generator that is supposed to give you a random quote along with the person who said it, but I've created two separate arrays because it'll make it easier to edit the visual aspects of the page later on. The first array has the quote itself and the second array has the names of the people who said them. I would like to generate one random number and then use that as my index on both arrays, thus getting a random quote and the corresponding person who said it.

The first thing I tried was this:

var randomIndex = function() {
  return Math.floor(Math.random() * quotes.length);
};

button.addEventListener("click", function(){
  quoteBox.textContent = '"' + quotes[randomIndex()] + people[randomIndex()] + '"';
});

But that gives me two different random numbers (because I'm calling the function twice, I suppose). I then tried setting the random number to a variable and using that as the index, but that doesn't change unless I refresh the page and I want it to change on the click of a button. Is what I want to do possible?

解决方案

Try calling randomIndex inside your click handler.

button.addEventListener("click", function(){
  var random = randomIndex();
  quoteBox.textContent = '"' + quotes[random] + people[random] + '"';
});

That will assign a new index each time the click handler runs, but will use the same index to access both quotes and people.

这篇关于在多个地方使用相同的随机数(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆