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);
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] = [];
}
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.