How to choose a set of unique random numbers (no duplicates) using the jQuery.inArray method?

前端 未结 3 948
旧巷少年郎
旧巷少年郎 2020-12-21 04:07

This is a Javascript / jQuery question:

I\'m trying to generate six unique random numbers between 1 and 21 (no duplicates), using the jQuery.inArray

3条回答
  •  -上瘾入骨i
    2020-12-21 04:32

    // Initial number
    var x = Math.ceil(Math.random() * TotalLogos);
    
    // Keep searching until a unique number is found
    while ($.inArray(x, r) > -1) {
        x = Math.ceil(Math.random() * TotalLogos);
    }
    
    // If it's unique, set it
    r[t] = x;
    

提交回复
热议问题