ajHurliman
ajHurliman

Reputation: 136

JS: Why is my variable being assigned a function instead of calling the function?

I'm trying to set some random coordinates on a map. I wrote the console.log line to see if it was successfully picking numbers, but it's telling me that everything in my destinations array is NaN.

It looks like it's assigning the Math.random function to the variable instead of calling Math.random and giving it the number it returns. Anyone know what's up?

var nodeCount = 10
var mapSize = 100;

var destinations = new Array(nodeCount);
for (var i = 0; i < nodeCount; i++) {
    destinations[i] = new Array(2);
}

var generateDestinations = function(nodeCount) {
    for (var i=0; i<nodeCount; i++) {
        destinations[i][0] = Math.floor(Math.random*mapSize); //sets x-coord
        destinations[i][1] = Math.floor(Math.random*mapSize); //sets y-coord
        console.log(destinations);
    }
};
generateDestinations(nodeCount);

Upvotes: 0

Views: 64

Answers (2)

Ian Wise
Ian Wise

Reputation: 766

http://www.w3schools.com/jsref/jsref_random.asp

try this, looks like your defining a max value but not a min, (I am assuming you want a number between 0 and mapSize)

    //                         \/ max value
    Math.floor((Math.random()*mapSize) + 0);
    //                                   /\ min value

also Math.random is a function so its

Math.random()

Upvotes: 0

David G
David G

Reputation: 96865

Math.random() is a function, so it needs to be invoked with the call-operator:

Math.floor(Math.random() * mapSize);
//                    ^^

Same goes for the line below it.


Moreover, you can use the array literal syntax instead of calling the constructor. It's much cleaner and more expressive:

var destinations = [];
for (var i = 0; i < nodeCount; i++) {
    destinations[i] = [];
}

Upvotes: 2

Related Questions