简体   繁体   English

您如何使用JavaScript在一段时间内从数组中获取随机结果?

[英]How do you use javascript to get a random result from an array over a time interval?

I want the function tim below to get an ever changing route from Array every 500 milliseconds. 我希望下面的函数tim每500毫秒从Array获得一条不断变化的路由。 Instead, in my JS console I receive the following repeating error: 相反,在我的JS控制台中,我收到以下重复错误:

VM5550:1 Uncaught SyntaxError: Unexpected end of input VM5550:1未捕获的语法错误:输入的意外结束

What is going on here and what do I need to do to get the result I'm looking for? 这是怎么回事,我需要做些什么才能获得想要的结果?

My code: 我的代码:

var Array = ["http://files.parsetfss.com/9.png", 
"http://files.parsetfss.com/5.png",
"http://files.parsetfss.com/6.png",
"http://files.parsetfss.com/7.png",
"http://files.parsetfss.com/8.png"];

var sampl = _.first(_.sample(Array, 1));
var tim = setInterval(sampl, 500);

I also tried wrapping sample in a function like so: 我还尝试将示例包装在如下函数中:

var sampl = function(){return _.first(_.sample(Array, 1))};

I'm still not getting the desired result but now I'm getting a result that is consistently even 7 or 11 (after refeshing the screen a number of times. 我仍然没有得到想要的结果,但是现在我得到的结果始终是7或11(刷新屏幕多次后)。

First, you should definitely change the name of your var to something else instead of overwriting the Array object. 首先,您绝对应该将var的名称更改为其他名称,而不是覆盖Array对象。

Next, the _.first seems unnecessary. 接下来, _.first . _.first似乎不必要。 A sample of 1 is returning a string. 样本1返回一个字符串。

Run the snippet to see the desired effect. 运行该代码段以查看所需的效果。

 var arr = [ "http://files.parsetfss.com/9.png", "http://files.parsetfss.com/5.png", "http://files.parsetfss.com/6.png", "http://files.parsetfss.com/7.png", "http://files.parsetfss.com/8.png" ]; var tim = setInterval( function() { document.body.innerHTML = _.sample(arr); }, 500); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script> 

You need to pass a function to setInterval , whereas you're passing it the result of running your array through underscore's first and sample methods (which in your case is a string). 您需要将一个函数传递给setInterval ,而要通过下划线的firstsample方法(在您的情况下为字符串)将数组运行的结果传递给该函数。 As @Tony points out, the use of first is unnecessary since the second parameter of the sample method specified the number of results you expect (see documentation ). 正如@Tony所指出的,因为sample方法的第二个参数指定了您期望的结果数量(请参阅文档 ),所以不需要使用first

The following does what I think you're looking for: 以下是我想您正在寻找的:

var array = ["http://files.parsetfss.com/9.png", 
"http://files.parsetfss.com/5.png",
"http://files.parsetfss.com/6.png",
"http://files.parsetfss.com/7.png",
"http://files.parsetfss.com/8.png"];

function getRandom() {
    return _.sample(array, 1)[0];
} 

function showRandom() {
    console.log(getRandom());
}

// setInterval returns a pointer to the interval ...
var interval = setInterval(showRandom, 500);

// ... which you can use to stop it
//clearInterval(interval);

You can use this function to get random element from array like this: 您可以使用此函数从数组中获取随机元素,如下所示:

var url = getRandomeEle(array);

function getRandomEle(arr) {
   return arr[~~(Math.random()*arr.length)];
}

Good answers already and I agree with Tony that you really should change the variable name Array . 已经有了很好的答案,我也同意Tony的观点,您确实应该更改变量名称Array

I presume you will want to stop this interval at some point in which case you will need to call clearInterval . 我想您会在某个时候停止此间隔,在这种情况下,您需要调用clearInterval

Here's a quick DEMO . 这是一个快速的DEMO

script.js script.js

var intervalId,

    startButton = document.getElementById('start'),
    stopButton  = document.getElementById('stop'),

    urls = [
      "http://files.parsetfss.com/9.png", 
      "http://files.parsetfss.com/5.png",
      "http://files.parsetfss.com/6.png",
      "http://files.parsetfss.com/7.png",
      "http://files.parsetfss.com/8.png"
    ];

startButton.addEventListener('click', tim, false);
stopButton.addEventListener('click', stopTim, false);


function tim() {
  intervalId = setInterval(printRandomUrl, 500);
}

function stopTim(){
  clearInterval(intervalId)
}

function printRandomUrl(){
  console.log(_.sample(urls));
}

index.html index.html

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="jquery" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script data-require="lodash.js@3.8.0" data-semver="3.8.0" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.8.0/lodash.js"></script>

  </head>

  <body>
    <h1>Basic plunk!</h1>
     <button id="start">Start</button>
     <button id="stop">Stop</button>

     <script src="script.js"></script>
  </body>

</html>

暂无
暂无

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

相关问题 Javascript,我如何从数组中获取两个相应的元素以使用随机功能同时生成? - Javascript, how do i get two corresponding elements from an array to generate at the same time with the random feature? 如何从 Javascript 中的数组中获取元素的随机组合? - How do i get a random combination of elements from an array in Javascript? 如何使用数组中的随机元素,从数组中删除该元素,并继续使用随机元素直到数组为空? - How do you use a random element from an array, remove that element from the array, and keep using random elements until the array is empty? 您如何通过键从 JavaScript 字典数组中获取 object? - How do you get an object from an array of JavaScript dicts by key? JavaScript 中的 timeout 和 interval 是否使用单调时间? - Do timeout and interval in JavaScript use monotonic time? Javascript问题:将鼠标悬停在div上时如何从颜色数组更改标题的随机颜色? - Javascript problem: How do I change random color of heading from array of colors when hovering over div? Javascript - 你如何找到一个数字随时间的总增长? - Javascript - How do you find the total increase of a number over time? 如何获取js以查找此数组中的随机数总和? - How do you get js to find the sum of random numbers in this array? 每次页面刷新时,如何将JavaScript文件中的随机图像加载到HTML中? - How do I load a random image from an array in a JavaScript file into HTML every time the page refreshes? javascript中如何在一个时间间隔内做一个任务 - How to do a task in a time interval in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM