簡體   English   中英

JS:為什么為變量分配一個函數而不是調用該函數?

[英]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()

為什么我的JS function 只操作一個<div>分配給 class 而不是全部?</div><div id="text_translate"><p> 我有這個 JS function 應該最初隱藏一個具有 class 名稱“tw”的,當點擊一個按鈕時它應該使它可見。 但是,每當我單擊按鈕時,它只會更改一個 div 的可見性。 我有 4 個。我該如何解決這個問題?</p><pre> function myFunction(){ var elms = document.getElementsByClassName("tw"); Array.from(elms).forEach((x) =&gt; { if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } }) }</pre><p> <a href="https://jsfiddle.net/qm8bxryh/307/" rel="nofollow noreferrer">https://jsfiddle.net/qm8bxryh/307/</a>這是小提琴</p></div>

[英]Why does my JS function only manipulate one <div> that is assigned to the class instead of all?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM