samedi 6 août 2016

Javascript, getting NaN when working with array

recently I've been working with JavaScript, and I have to say, I am not very good at it. My problem lies in making a raffle game, everytime I want to get a random number from my array, the output get undefined, and the console output tells me that my return is NaN(not a number).

So what I did was defining an array at the top of my script:

var competitors = new Array();

Then, I've got these 2 if clauses, the first one should add message.author.name to the array.

if(input == ".JOIN") {
        if(raffling) {
            competitors.push(message.author.name);
            bot.sendMessage(message, "@" + message.author.name + " has joined the raffle")
        }
    }

The second one is to determine a random entry from that array, and then print out the 'raffle-winner'.

if(input == ".RTD") {
        if(raffling) {
            if(competitors.length > 0) {
                bot.sendMessage(message, "The winner is: " + competitors[Math.floor(Math.random() * (competitors.lenght))]);
                raffling = false;               
            }
        }
    }

But whenever I use that, the output from bot.sendMessage is undefined (it's the standard print function) and the console tells me that the winner is NaN. I'll make sure to add any missing parts of code, if there are any.




Aucun commentaire:

Enregistrer un commentaire