1

I would like to be able to take out the result of a timed event, but I am not sure how to find the index for it. The problem is that I am choosing an item from the array by time, but by index number, so I need to be able to get the result after the timer has run.

It will be along the lines of

mixedgroup1.splice(i, 1);

where i is the index number of the final result, but I cannot tell how to get it.

Any ideas?

Here is the JS code:

var basket = ['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig', 'grapes', 'huckleberry', 'kiwi', 'lemon', 'mango'];

 function randOrd(){
return (Math.round(Math.random())-0.5); } 

 mixedBasket = basket.sort( randOrd ); //randomize the array

 var i = 0;  // the index of the current item to show


 function showBasket(){
 fruitDisplay = setInterval(function() {            
    document
        .getElementById('fruit')
        .innerHTML = mixedBasket[i++];    // get the item and increment
    if (i == mixedBasket.length) i = 0;   // reset to first element if you've reached the end
 }, 70);  //speed to display items

 var endFruitDisplay = setTimeout(function( ) { clearInterval(fruitDisplay); }, 3600); 
 //stop display after x milliseconds
}

and this is the HTML:

<html>

<head></head>
<body>


<center>
   <h1> <span id="fruit"></span><p></h1>
 <script> var fruitSound = new Audio(); 
        fruitSound.src = "boardfill.mp3"; 

    function showFruitwithSound()
    { 
    fruitSound.play(); // Play button sound now 
    showBasket()
    } 

 </script>

<button onclick="showFruitwithSound()">Choose Fruit</button>

</center> 

<script type="text/javascript" src="Fruitpicker3.js"></script>
</body>
</html>
4

2 回答 2

0

以下是如何获取最终结果的索引:

mixedBasket.indexOf(document.getElementById('fruit').innerHTML);

在此处添加:

var endFruitDisplay = setTimeout(function( ) { 
        clearInterval(fruitDisplay); 
        var index = mixedBasket.indexOf(document.getElementById('fruit').innerHTML); 

        //do splice and stuff

        document.getElementById("indexnum").innerHTML = index;    
    }, 3600); 
于 2014-12-21T22:43:39.713 回答
0

抱歉这么密集,但我对js相当陌生。我根本无法得到任何输出。这是重写:

 <center>
 <h1> <span id="fruit"></span><p></h1> 

   <script> var fruitSound = new Audio(); 
    fruitSound.src = "boardfill.mp3"; 

    function showFruitwithSound()
    { 
    fruitSound.play(); // Play button sound now 
    showBasket()
    } 

 </script>

 <p id = "indexnum">
 <button onclick="showFruitwithSound()">Choose Fruit</button>

   </center> 
 <script>  
 var indexf = mixedBasket.indexOf(document.getElementById('fruit').innerHTML);
 document.getElementById("indexnum").innerHTML = indexf + " this is the index number."; 
 </script>

  <script type="text/javascript" src="Fruitpicker3.js"></script>
 </body>

于 2014-12-22T16:14:07.513 回答