admin管理员组文章数量:1434960
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'?
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'?
Share Improve this question asked May 26, 2016 at 23:50 mdevmdev 256 bronze badges 2-
6
|
is bitwise OR. It's a "clever" way to truncate the floating-point result ofMath.random() * i
to an integer. – Blorgbeard Commented May 26, 2016 at 23:52 - Possible duplicate of What does the "|" (single pipe) do in JavaScript? – Martin Gottweis Commented May 26, 2016 at 23:53
3 Answers
Reset to default 8The bitwise OR operator | converts its input to a 32-bit two-plement number. This is often used for fast rounding towards zero (faster than 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
therefore equals Math.trunc(Math.random() * i)
and returns pseudo-random integers in the range from 0 to i - 1.
PS: A double bitwise negation ~~ has the same effect. 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-plement (2³¹ - 1).
Math.random()
gives you random floating-point in range [0, 1)
. Multiplying it by i
in loop gives you weird values. | 0
gives you integer part of value. Math.floor(Math.random()*n)
returns random integer in range [0, n)
, which seems applicable.
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.
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
so you just reshuffle first 10 nodes placing random one at the end of list.
Math.random() * N)
- Get a random number with Digits and between 0 and N, it can be equal to 0 but cannot be equal to N
Math.random() * N) | 0
- Get a random number without Digits (the digits are being dropped without any condition) the result also would be between 0 and N, it can be equal to 0 but cannot be equal to N
本文标签: javascriptWhat does Mathrandom() * i0 meanStack Overflow
版权声明:本文标题:javascript - What does Math.random() * i | 0 mean? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745618123a2666522.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论