最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论
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

发布评论

评论列表(0)

  1. 暂无评论