Javascript Math.random()和条件表达式

时间:2018-03-18 17:03:49

标签: javascript if-statement random colors nodes

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

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"

3 个答案:

答案 0 :(得分:1)

语法:

$.ajax({
    url: "crossdomainurl",
    type: "GET",
    contentType: 'text/plain'
}); 

意思是:

  • let expression = (random < 1 / (i + 1)); 首先将1添加到var (i + 1)
  • 接下来,i将1除以总和1 / (i + 1)
    • 让我们说(i + 1)
  • result = 1 / (i + 1),如果小于random < result的随机值,则返回true,否则返回false。

所以,简单的事情:

result

答案 1 :(得分:0)

我首先想到它会被随机评估&lt; 1然后随机使用Math.random()得到0到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;
};

答案 2 :(得分:0)

此:

  

我无法尝试知道表达式的含义

在这里给出:

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

math.Random返回0到1之间的一个浮点数,并将其放入random。整个右侧评估为布尔值 - True或false,因为< 是应用的最后一个操作。您可以检查https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence是否有完整的操作顺序。因此,expression只包含一个True或False值,具体取决于当前随机数是否小于1/i+1