Reputation: 33
I've got array od values, and I want to take random from it. This is my code:
var bonus1='Opony zimowe';
var bonus2='Alarm';
var bonus3 = 'Bagażnik';
var bonus4 = 'Relingi';
var bonus5 = 'Box na narty';
var bonusy = [bonus1, bonus2, bonus3, bonus4, bonus5];
var pickBonus= bonusy[Math.floor(Math.random() * bonusy.length)];
But it doesn't show random value (Its always console.log - 'Alarm'):
What is wrong?
Upvotes: 1
Views: 86
Reputation: 1263
replace the last line
var pickBonus= bonusy[Math.floor(Math.random() * (bonusy.length-1)) + 1]
and wrap the whole code in a function to populate new pickBonus
value in each function call
Upvotes: 1
Reputation: 14641
pickBonus
should be a function and not a variable in your case.
Then you can run this type of code and always get random values:
var bonus1 = 'Opony zimowe';
var bonus2 = 'Alarm';
var bonus3 = 'Bagażnik';
var bonus4 = 'Relingi';
var bonus5 = 'Box na narty';
var bonusy = [bonus1, bonus2, bonus3, bonus4, bonus5];
function pickBonus() {
return bonusy[Math.floor(Math.random() * bonusy.length)];
}
console.log(pickBonus());
console.log(pickBonus());
console.log(pickBonus());
console.log(pickBonus());
Upvotes: 2
Reputation: 68443
From your screenshot it appears that you are basically trying to print the same value multiple times expecting a different value.
It won't work, you need to get the random value again from the array every time. Make it into a function
var pickBonus= () => bonusy[Math.floor(Math.random() * bonusy.length)];
And now invoke it as
console.log( pickBonus() );
console.log( pickBonus() );
console.log( pickBonus() );
console.log( pickBonus() );
Demo
var bonus1='Opony zimowe';
var bonus2='Alarm';
var bonus3 = 'Bagażnik';
var bonus4 = 'Relingi';
var bonus5 = 'Box na narty';
var bonusy = [bonus1, bonus2, bonus3, bonus4, bonus5];
var pickBonus= () => bonusy[Math.floor(Math.random() * bonusy.length)];
console.log( pickBonus() );
console.log( pickBonus() );
console.log( pickBonus() );
console.log( pickBonus() );
Upvotes: 10