javascript - What does Math.random() * i | 0 mean? - Stack Overflow

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

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 of Math.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
Add a ment  | 

3 Answers 3

Reset to default 8

The 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745618123a4636357.html

相关推荐

  • javascript - What does Math.random() * i | 0 mean? - Stack Overflow

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

    9小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信