【问题标题】:Javascript Math.random() and conditional expressionsJavascript Math.random() 和条件表达式
【发布时间】:2018-08-27 06:47:17
【问题描述】:

我想与您分享我对这段代码的看法:

for (var i = 1, max = 5; i < max; i++) {
    let random = Math.random();
    let expression = (random < 1 / (i + 1));
    if (expression){
        console.log('random is: ' + random + ' and the expression is: ' + expression + ', i is: ' +     i);
    }else{
        console.log('random was: ' + random + ' and the expression was: ' + expression + ', i was: ' + i);
    }
}

我正在研究这个取自 GitHub 的示例:https://github.com/chuckha/ColorFlood

而且我很难知道 if() 中的表达式的含义。

我使用了 JS repl:https://jscomplete.com/repl/

这个例子的上下文是,这个函数将使用一个从 0 到 5 的随机索引,以将随机颜色映射到一个节点。

这里有一个来自 repl 的示例输出:

"random was: 0.7118559117992413 and the expression was: false, i was: 1"
"random was: 0.478919411809795 and the expression was: false, i was: 2"
"random was: 0.4610390397998597 and the expression was: false, i was: 3"
"random was: 0.7051121468181564 and the expression was: false, i was: 4"

【问题讨论】:

    标签: javascript if-statement random colors nodes


    【解决方案1】:

    语法:

    let expression = (random < 1 / (i + 1));
    

    意思是:

    • (i + 1) 先将 1 加到 var i
    • 接下来,1 / (i + 1) 将 1 除以总和 (i + 1)
      • result = 1 / (i + 1)
    • random &lt; result,如果随机值小于上述除法result,则返回true,否则返回false。

    所以,像这样简单的事情:

    for (var i = 1, max = 5; i < max; i++) {
      let random = Math.random();
      let expression = (random < 1 / (i + 1));
      console.log(
        i,
        random.toFixed(2),      
        (1 / (i + 1)).toFixed(2), 
        expression
      )
    }

    【讨论】:

      【解决方案2】:

      我首先认为它会被评估为 random

      但其实放到repl里面后发现是先做1/(i+1)部分,然后全部一起做:random/result。

      我也看过:

      https://www.w3schools.com/js/js_comparisons.asp

      https://www.w3schools.com/js/js_arithmetic.asp

      https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/random

      请注意,在原帖中我简化了代码,原代码是:

      var randomIndexFromCollection = function randomIndexFromCollection(collection) {
        var index = 0;
        for (var i = 1, max = collection.length; i < max; i++) {
          if (Math.random() < 1 / (i + 1)) {
            index = i;
            debugger;
          }
        }
        return index;
      };
      

      【讨论】:

      • 检查是这样的:Math.random() 是否小于 1 / (i + 1),如果是,则返回 true,否则返回 false。它不能是随机/结果,因为那里有一个相等运算符比较两侧。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      相关资源
      最近更新 更多