[英]JS: Why is my variable being assigned a function instead of calling the function?
我正在嘗試在地圖上設置一些隨機坐標。 我寫了console.log行,看它是否成功選擇了數字,但這是告訴我destinations
數組中的所有內容都是NaN。
看起來好像是將Math.random函數分配給變量,而不是調用Math.random並給它返回的數字。 有人知道怎么回事嗎?
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()
是一個函數,因此需要使用call-operator進行調用:
Math.floor(Math.random() * mapSize);
// ^^
下面的行也一樣。
此外,您可以使用數組文字語法而不是調用構造函數。 它更干凈,更富有表現力:
var destinations = [];
for (var i = 0; i < nodeCount; i++) {
destinations[i] = [];
}
http://www.w3schools.com/jsref/jsref_random.asp
試試看,看起來像您定義的是一個最大值,而不是一個最小值,(我假設您想要一個介於0和mapSize之間的數字)
// \/ max value
Math.floor((Math.random()*mapSize) + 0);
// /\ min value
也是Math.random是一個函數,所以它
Math.random()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.