0

I can’t seem to understand this loop.

for (i = 1; i < 50; i++) {
    rand = Math.ceil(Math.random() * 49);
    temp = nums[i];
    nums[i] = nums[rand];
    nums[rand] = temp;
}

It is part of a larger code. nums[i] is an array of 1-49 filled with their respective index numbers, then it is run through this for loop and filled with random numbers.

I don’t understand why the temp variable is created, how the nums[rand]=temp; line of code works and what does it do, and why is it not even initialized without the var keyword.

Can someone explain how this loop works?

4

2 回答 2

1

What the code attempts to do is to shuffle the array. It works by going through the array, and for each position, store the value in a temp variable, pick another position in the array and swap the values with the other position.
The temp variable is required as this is the most simple way to swap the values of the variables.

于 2012-07-09T09:29:35.973 回答
1

It's just randomly swapping two values in the nums array. Although ignoring the very first one; javascript arrays start at 0, but the loop only starts at 1, so it only starts from the 2nd array element.

So stepping through the code, every time it goes round the loop it does something like this:

nums = [a, b, c];  // just mocking some data

rand = 0..2;  // lets say it = 2
temp = nums[1]; // = 'b', the 2nd array element
nums[1] = temp;  // so nums[1] goes from 'b' to 'c'
nums[temp] = temp; // and nums[2] goes from 'c' to 'b'

overall it's pretty bad code. If it's working with an array it should use array.length instead of hardcoding 50 for the upper limit of the loop.

于 2012-07-09T09:31:05.290 回答