私は変数を持っています..
var random = Math.ceil(Math.random() * 8.8);
クリック機能があります
$('.passShort').bind('click', function() {
// do something here and get new random number
});
この特定の関数内だけでなく、グローバルランダム変数を変更しようとしています。
私は変数を持っています..
var random = Math.ceil(Math.random() * 8.8);
クリック機能があります
$('.passShort').bind('click', function() {
// do something here and get new random number
});
この特定の関数内だけでなく、グローバルランダム変数を変更しようとしています。
真にグローバルである必要がある場合は、グローバル変数を厳密に定義するのが好きで、可能な場合はコードの繰り返しを避けます。
setRandom();
$('.passShort').bind('click', setRandom);
function setRandom() { window.random = Math.ceil( Math.random() * 8.8 ); };
オブジェクトに変数を設定すると、window
真にグローバルになります。random
どこでも参照できますが、グローバル変数の値を設定していることwindow.random
をwindow.random
保証します。random
関数の外で使用var
しますが、内部では使用しません:
var random = Math.ceil(Math.random() * 8.8);
$('.passShort').bind('click', function() {
random = Math.ceil(Math.random() * 8.8);
});
変数を宣言した場所に応じて、その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.
});