-1

我需要一个数组中有 10 个不同的随机数。

我正在使用以下功能:

    for (k=0;k<10;k++) {
      x[k] = Math.floor((Math.random()*10));
      for (l=0;l<k;l++){
        if (x[l]==x[k]){fail=true;}
      }
      if (fail){k=k-1;}
    }

THX 回答。

4

4 回答 4

3

Make sure all your variables are declared:

var x = [], k, l, fail;

Make sure you reset "fail" before the inner loop:

  fail = false;
  for (l = 0; l < k; l++)
    // ...

Now that said, if you want 10 numbers in an array, and the array is 10 elements long, you're better off filling the array with the numbers from 1 to 10 (or 0 to 9; whatever) and then shuffling the array. If you do things your way, then the performance of the process is unpredictable. When you get to the last couple of elements, it may take two or three tries, or it may take hundreds; you never know what the random number sequence may do.

于 2013-06-01T13:14:58.300 回答
3

It would be better to fill the array with numbers from 1 to 10, and then shuffle it, like this:

var myArray = [1,2,3,4,5,6,7,8,9,10];

//shuffle array
//code from http://stackoverflow.com/a/2450976/1223693
var i = myArray.length, j, temp;
if ( i === 0 ) return false;
while ( --i ) {
   j = Math.floor( Math.random() * ( i + 1 ) );
   temp = myArray[i];
   myArray[i] = myArray[j]; 
   myArray[j] = temp;
}

//done
alert(myArray);

Your current method is very slow because

  • it has an inner loop
  • it may generate wrong numbers many many times before it generates a correct number
于 2013-06-01T13:16:06.763 回答
1

You really want to have a array with 10 elements with random numbers between 0 and 9 and none of it is allowed to be the same? So you want to have the numbers 0-9 in 10 Elements shuffled around?

Then just init them and shuffle them:

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};


// init the array:
var a = new Array();
for (var i=0;i<10;i++){
  a.push(i);
} 
// shuffle it.
a = shuffle(a);
于 2013-06-01T13:19:05.077 回答
1

可以更简单——

var nums= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].sort(
function(){return Math.random()-.5});
于 2013-06-01T13:41:43.047 回答