简体   繁体   English

Math.random()* i |是什么? 0是什么意思?

[英]What does Math.random() * i | 0 mean?

var lst = [/*List of items*/];
for (var i = 10; i > 0; i--) {
    lst.appendChild(lst[Math.random() * i | 0]);
}

Why would "|" 为什么会“ |” be in a index? 在索引中? Does this function shuffle the list 'lst'? 此功能是否会打乱列表“ lst”?

The bitwise OR operator | 按位或运算符 | converts its input to a 32-bit two-complement number. 将其输入转换为32位二补数。 This is often used for fast rounding towards zero (faster than Math.trunc()): 通常用于快速舍入为零(比Math.trunc()更快):

 console.log(1.1 | 0); // 1 console.log(1.9 | 0); // 1 console.log(-1.1 | 0); // -1 console.log(-1.9 | 0); // -1 

The expression Math.random() * i | 0 表达式Math.random() * i | 0 Math.random() * i | 0 therefore equals Math.trunc(Math.random() * i) and returns pseudo-random integers in the range from 0 to i - 1. 因此Math.random() * i | 0等于Math.trunc(Math.random() * i)并返回从0到i-1范围内的伪随机整数。

PS: A double bitwise negation ~~ has the same effect. PS:双重按位取反~~具有相同的效果。 Keep in mind that applying bitwise operators effectively reduces the range of integer operands from Number.MAX_SAFE_INTEGER (2⁵³ - 1) to the maximum 32-bit two-complement (2³¹ - 1). 请记住,应用按位运算符可以有效地减少整数操作数的范围,从Number.MAX_SAFE_INTEGER(2⁵³-1)到最大32位二补码(2³¹-1)。

Math.random() gives you random floating-point in range [0, 1) . Math.random()为您提供范围[0, 1)随机浮点。 Multiplying it by i in loop gives you weird values. 在循环中将其乘以i可得到怪异的值。 | 0 | 0 gives you integer part of value. | 0给出值的整数部分。 Math.floor(Math.random()*n) returns random integer in range [0, n) , which seems applicable. Math.floor(Math.random()*n)返回范围为[0, n)随机整数,这似乎适用。

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. Node.appendChild()方法将一个节点添加到指定父节点的子节点列表的末尾。

but

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position 如果给定的子项是对文档中现有节点的引用,则appendChild()将其从其当前位置移至新位置

so you just reshuffle first 10 nodes placing random one at the end of list. 因此,您只需重新排列前10个节点,即可在列表末尾随机放置一个。

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

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