简体   繁体   中英

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'?

The bitwise OR operator | converts its input to a 32-bit two-complement 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 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-complement (2³¹ - 1).

Math.random() gives you random floating-point in range [0, 1) . Multiplying it by i in loop gives you weird values. | 0 | 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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