2017-06-24 4 views
0

Ich möchte ein Array mit Variablen erstellen und diese Variablen sollten sich nach einer bestimmten Zeit ändern.Hier ist mein Code, wenn jemand eine Idee hat, bitte sag es mir.Array mit variabler Änderung nach der Zeit

 var cookieArray = new Array(window.setInterval(myCallback, 2000)); 

     function myCallback() { 

       cookie1 = Math.floor((Math.random() * 810) + 0); 
       cookie2 = Math.floor((Math.random() * 810) + 0); 
       cookie3 = Math.floor((Math.random() * 810) + 0); 
       cookie4 = Math.floor((Math.random() * 810) + 0); 
       cookie5 = Math.floor((Math.random() * 810) + 0); 
       cookie6 = Math.floor((Math.random() * 810) + 0); 
       cookie7 = Math.floor((Math.random() * 810) + 0); 
       cookie8 = Math.floor((Math.random() * 810) + 0); 
       cookie9 = Math.floor((Math.random() * 810) + 0); 
       cookie10 = Math.floor((Math.random() * 810) + 0); 
     } 

PS: sorry für mein schlechtes englisch, aber ich bin noch Schüler: D

Antwort

1

Sie ein Array kreierten, sondern initialisiert es nicht. Um ein Array zu initialisieren, sollten Sie in Ihrem Fall arrayName[0]=value verwenden.

var cookieArray =[]; 
 
    
 
window.setInterval(myCallback, 2000); 
 

 
function myCallback() { 
 
     cookieArray[0] = Math.floor((Math.random() * 810) + 0); 
 
     cookieArray[1] = Math.floor((Math.random() * 810) + 0); 
 

 
     console.log(cookieArray); 
 
} 
 
    

+0

ah ok danke. – Yuto

0

Der Ansatz, den Sie OK nahm, ist aber eine Menge Programmierfehler enthält. Zu allererst Sie Array zu deklarieren, müssen Sie folgendes tun:

var cookieArray = new Array(10); 

, die die cookieArray Mittel 10 Elemente haben. Um auf jedes einzelne seiner Elemente zuzugreifen, können Sie cookieArray[i] verwenden, wobei sich i auf das i + 1 te Element des Arrays bezieht.

Am Ende ich tun würde:

var cookieArray = new Array(10); 

setInterval(function() { 
    for(int i = 0; i < cookieArray.length; i++) { 
     cookieArray[i] = Math.floor((Math.random() * 810) + 0); 
    } 
}, 2000); 

hier, setInterval die gleiche wie window.setInterval ist.

+0

ah okay danke. – Yuto

1

Sie könnten auch tun:

var cookieArray=(new Array(10)).fill(0);//create a new Array with 0s 

setInterval(function(){ 
    //refill array every 2seconds 
    cookieArray=cookieArray.map(()=>Math.floor((Math.random() * 810) + 0)); 
},2000); 
+0

ah okay danke. – Yuto

Verwandte Themen