samedi 6 novembre 2021

Javascript loop an array, but the value didn't foward

I hava an array generate by PHP server side, battleinfo. After that, I would like to use JavaScript to loop the array, final output should be

//what i want like below
//example, first aaa is 0 random by Math.floor(Math.random() * (max - min + 1));
11:40:01 monkey first 
11:40:06 hp-100
11:40:11 win
11:40:16 squrriel //when the battle[0] has been reach end of array, new aaa random, get value 2
11:40:21 hp-1000
11:40:26 win money 1000
11:40:31 monkey //random again when battle[2] has been finish.

But, my current error is aaa will be undefined, now output like below:

11:40:01 money
11:40:06 undefined
11:40:11 undefined
11:40:16 undefined //loop forever

Attach with snippet, please help and thank you.

var battleinfo = [
    ["monkey","hp-100","win"],
    ["crocok","hp-200","win money 100"],
    ["squrriel","hp-1000","win money 1000"],
];

var mystart = 0;

var battleinput = setInterval(function(){
    var date = new Date();
    var hour = ("0" + date.getHours()).substr(-2);
    var minutes = ("0" + date.getMinutes()).substr(-2);
    var seconds = ("0" + date.getSeconds()).substr(-2);
    
    
    if(mystart <= 0){
        var bb = 0;
        var infocount = battleinfo.length;
        min = 1;
        max = Math.floor(infocount);
        
        var aaa = Math.floor(Math.random() * (max - min + 1));//get random number, to decide which array to be show in div
        var mystart = battleinfo[aaa].length;//count the array have how many value to be show in div

        var randomItem = battleinfo[aaa][bb];//inset
        mystart--;
        bb++;
    }else{
        alert(aaa);
        //HERE, aaa AND bb will be undefined value
        var randomItem = battleinfo[aaa][bb];
        bb++;
    }

    document.getElementById("advanturerun").innerHTML = "<pre>" + hour + ":" + minutes + ":" + seconds + " " + randomItem  + "\n" + "</pre>" + document.getElementById("advanturerun").innerHTML;
}, 5000);
<div id="advanturerun">&nbsp;</div>



Aucun commentaire:

Enregistrer un commentaire