[英]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. 我写了console.log行,看它是否成功选择了数字,但这是告诉我destinations
数组中的所有内容都是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. 看起来好像是将Math.random函数分配给变量,而不是调用Math.random并给它返回的数字。 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.random()
是一个函数,因此需要使用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 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) 试试看,看起来像您定义的是一个最大值,而不是一个最小值,(我假设您想要一个介于0和mapSize之间的数字)
// \/ max value
Math.floor((Math.random()*mapSize) + 0);
// /\ min value
also Math.random is a function so its 也是Math.random是一个函数,所以它
Math.random()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.