2013-02-18 76 views
0

我有一個變種..JavaScript的隨機數重新上點擊

var random = Math.ceil(Math.random() * 8.8); 

,我有

$('.passShort').bind('click', function() { 
    // do something here and get new random number 
}); 

我試圖改變不只是這裏面尤其是全局隨機VAR點擊功能功能。

+0

我們可以看到第一個代碼塊和第二個代碼塊如何組合在一起? – 2013-02-18 03:54:19

+0

@ExplosionPills我認爲這是OP的要求。 – iambriansreed 2013-02-18 04:06:16

回答

0

使用var功能外,但不是在它裏面:

var random = Math.ceil(Math.random() * 8.8); 
$('.passShort').bind('click', function() { 
    random = Math.ceil(Math.random() * 8.8); 
}); 
0

根據你聲明的變量random將決定它的範圍。如果您想使其成爲全球性的,只需聲明它不帶var關鍵字。

random = Math.ceil(Math.random() * 8.8); 

真的,它會更好,如果你可以結合你正在尋找到一些可重用的對象的功能,隨機數發生器?一個例子可能是:

var RNG = {  
    get randInt() { return Math.ceil(Math.random() * 8.8); }, 
    get randFloat() { return Math.random() * 8.8; }, 
    randRange: function(min, max) { 
    return min + Math.floor(Math.random() * (max - min + 1)); 
    } 
}; 

console.log(RNG.randInt); 
console.log(RNG.randFloat); 
console.log(RNG.randRange(5,10)); 

$('.passShort').bind('click', function() { 
    console.log(RNG.randInt); // Whatever you want here. 
}); 
1

我喜歡當他們需要真正的全球性嚴格定義全局變量,我避免重複代碼時可能:

setRandom(); 

$('.passShort').bind('click', setRandom); 

function setRandom() { window.random = Math.ceil(Math.random() * 8.8); }; 

window對象確保設置變量它確實是全球性的。您可以將它引用爲random任何地方,它會給您window.random,但使用window.random可確保您設置全局random變量的值。