代码之家  ›  专栏  ›  技术社区  ›  Enoy

Javascript数学。random()和条件表达式

  •  -1
  • Enoy  · 技术社区  · 7 年前

    我想与您分享我对该代码的想法:

    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"
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   palaѕн    7 年前

    语法:

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

    指:

    • (i + 1) 首先将1添加到var i
    • 下一个 1 / (i + 1) 用1除以和 (i+1)
      • 比如说 result = 1 / (i + 1)
    • random < 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
  •  0
  •   Enoy    7 年前

    我最初认为它将被随机评估<1所以随机使用数学。random()获取0到1之间的数字,不包括1;我以为这句话的一部分永远是真的。

    但事实上,在将其放入repl后,我发现1/(I+1)部分首先完成,然后全部完成:随机/结果。

    我也读过:

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