Reputation: 41
I am trying to create a program that will give me the number of times the dice landed on a number after rolling 1000 times. It is returning the result of every roll to me and I only want it to return the last one. Thoughts?
var dice1 = {};
for (var i = 0; i < 1000; i++) {
var dieValue = [1, 2, 3, 4, 5, 6];
var randomRoll = Math.ceil(Math.random()* this.dieValue.length);
if(randomRoll in dice1) {
dice1[randomRoll]++;
}
else {
dice1[randomRoll] = 1;
}
console.log(dice1);
}
Upvotes: 0
Views: 413
Reputation: 36599
Remove this
as you are not referring a property in the this
context but using a variable. Also note, you should log
it out of the loop
var dice1 = {};
for (var i = 0; i < 1000; i++) {
var dieValue = [1, 2, 3, 4, 5, 6];
var randomRoll = Math.ceil(Math.random() * dieValue.length);
if (randomRoll in dice1) {
dice1[randomRoll] ++;
} else {
dice1[randomRoll] = 1;
}
}
console.log(dice1);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Upvotes: 1
Reputation: 31883
If you only want to log the last roll, put the log statement outside the for loop:
var dice1 = {};
for (var i = 0; i < 1000; i++) {
var dieValue = [1, 2, 3, 4, 5, 6];
var randomRoll = Math.ceil(Math.random()* this.dieValue.length);
if(randomRoll in dice1) {
dice1[randomRoll]++;
}
else {
dice1[randomRoll] = 1;
}
}
console.log(dice1);
Upvotes: 1