2016-03-17 68 views
0

我正在嘗試創建一個程序,該程序會在滾動1000次後給我骰子落在某個數字上的次數。它將每卷的結果返回給我,我只希望它返回最後一個。思考?顯示骰子滾動的次數

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); 

} 
+0

https://jsfiddle.net/arunpjohny/x38pL8q8/1/ –

回答

1

如果你只是想記錄的最後一個滾,把日誌語句外的for循環:

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); 
+0

感謝您的幫助。那就是訣竅! –

1

刪除this你不是在this中是指一個屬性,但使用變量。另外請注意,您應該log它圈外

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>

+0

'var dice1 = {}'將this.dice1'設置爲'{}'?例如。; 'var abc = 123; console.log(this.abc)' – guest271314

+0

'console.log(this.abc)'將會是'undefined'吧? – Rayon

+0

嘗試'var abc = 123; console.log(this.abc)'at'console' – guest271314