【问题标题】:showing the number of times dice rolled显示掷骰子的次数
【发布时间】:2016-03-17 04:20:08
【问题描述】:

我正在尝试创建一个程序,该程序将给出骰子在滚动 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);

}

【问题讨论】:

标签: javascript arrays loops javascript-objects


【解决方案1】:

如果只想记录最后一卷,请将 log 语句放在 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);

【讨论】:

    【解决方案2】:

    删除 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);
    &lt;script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • var dice1 = {} 是否将 this.dice1 设置为 {} ?例如。; var abc = 123; console.log(this.abc)
    • console.log(this.abc) 将是 undefined 对吗?
    • 试试var abc = 123; console.log(this.abc)console
    • @guest271314, function test() { var a = 10; console.log(this.a); } test();
    • 在铬,test() 返回undefined;虽然var a = 10; console.log(this.a) 记录10console
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2018-12-17
    • 2018-09-08
    • 2012-11-27
    • 2021-10-07
    • 2012-02-29
    相关资源
    最近更新 更多