繁体   English   中英

有人可以解释一下这段JavaScript代码的作用吗?

[英]Can someone please explain what this bit of javascript code is doing?

因此,我是编程的新手,试图了解这段JavaScript代码在做什么,特别是第3行和第4行,是对的,我假设它正在检查数组中随机生成的数字,如果数组中不存在该数字,则添加它然后如果是真的,会将那个数字放在文档ID中?

 var numarray = new Array(76); do { var rannum = Math.floor(Math.random() * 76) + 1; } while (numarray[rannum]); numarray[gNumber] = true; document.getElementById(cellID).innerHTML = rannum; 

var numarray= new Array(76);

它将创建包含76个元素的数组,

do {
           var rannum= Math.floor(Math.random() * 76) + 1;

这将为76分配一个数字

        } while (numarray[rannum]); 

这将遍历已定义的rannum元素,在您的情况下,它将始终未定义

 var numarray= new Array(76); do { var rannum= Math.floor(Math.random() * 76) + 1; console.log(rannum); } while (numarray[rannum]); console.log(numarray) 

总体而言,它会选择介于1到76之间的随机数,只要数组中与最后生成的随机数的索引匹配的项目具有非伪造的值,它将继续这样做。

在您的情况下,仅声明该数组具有76个索引位置,但从未填充该数组,因此该数组充满了undefined项目。

循环的while部分表示循环条件为numarry[random] ,这是一种测试以查看项目是否为任何“真实”值(不会隐式转换为“ false”或“ falsy”的任何值)的一种方式值,如0undefinednullNaNfalse"" )。 由于您的数组中充满了undefined项目,因此第一次检查循环条件时就不满足,并且循环仅循环一次迭代,从而仅生成一个随机数。

有关详细信息,请参见内联注释。

 var numarray = new Array(76); // Create new array with 76 indexed positions (or, a .length of 76) // Start a loop do { // Math.random() - Get a random number between 0 (inclusive) and 1 (exclusive) // * 76 - Take the random and multiply by 76 to get a random between 0 (inclusive) // and 76 (exclusive) // Math.floor() - Round the number down to the next whole number // + 1 - Instead of the range being 0 (inclusive) and 76 (exclusive) add an offset // so that the final number will be between 1 (inclusive) and 77 (exclusive) var rannum = Math.floor(Math.random() * 76) + 1; } while (numarray[rannum]); // Keep the loop going as long as the array item matching the random // isn't undefined, false, 0, NaN, null or "" (ie "truthy"). // In this case, the array is empty so the loop will only // iterate one time. // Set the array item that matches the gNumber value to true. // You haven't provided any code that declares or initializes gNumber, // so this line of code really is meaningless in this context. numarray[gNumber] = true; // Change the inner content (HTML and text) of the element with an id that matches // the value in cellID to the random number document.getElementById(cellID).innerHTML = rannum; 

资源:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM