Picking 2 random elements from array

前端 未结 9 890
一向
一向 2020-12-16 18:32

What is the most efficient way to select 2 unique random elements from an array (ie, make sure the same element is not selected twice).

I have so far:



        
9条回答
  •  有刺的猬
    2020-12-16 19:10

    Your code will hang when the list contains only one item. Instead of using ==, I recommend to use ===, which looks more suitable in this case.

    Also, use Math.floor instead of Math.ceil. The length property is equal to + 1.

    var elem1;
    var elem2;
    var elemListLength = elemList.length;
    
    elem1 = elemList[Math.floor(Math.random() * elemListLength)];
    if (elemListLength > 1) {
        do {
          elem2 = elemList[Math.floor(Math.random() * elemListLength)];
        } while(elem1 == elem2);
    }
    

提交回复
热议问题