jQuery Get Random Element From a Selection Returned By $(selector)

前端 未结 3 2276

If $(\'.my-element\') matches multiple element, is there a quick way to get a random element out of these?

3条回答
  •  你的背包
    2021-02-20 10:37

    To get an even distribution, you can multiply random by the array count and drop the decimal with the bitwise operator.

    var arr = ['a','b','c'];
    arr[~~(Math.random() * arr.length)]; //even odds of a, b, or c
    

提交回复
热议问题