### 如何隨機選擇任意范圍內的數字並使用JavaScript數組加在一起

#### [英]How to randomly select numbers within an arbitrary range and add together using JavaScript arrays

I am trying to write some JavaScript that will select some random numbers from an array and then add those selected numbers to make a single total value.

For example if i had `var array = [1, 22, 5, 88, 3, 105, 7, 88, 987]` i would then like the code to select however many numbers it wants at random(amount selected changes every time it runs) and then add them together but i am not sure if this is even possible.

I am new to JavaScript so i have only managed to write code that adds all the array elements together instead of selecting at random.

``````var arr = [1,2,3,4,5,6];
var total=0;
for(var i in arr) { total += arr[i]; }
``````

My code is very basic so please excuse me for this i'm still learning. Thank You

## 3 个解决方案

### #1

1

You could use the `Math.rand()` function in order to create a random index. In terms of code:

``````// The array with your elements
var arr = [1,2,3,4,5,6];

// An array that will keep track of the elements we have selected.
var selectedIndex = [];

// The sum.
var sum=0;

// times is the number of elements we want to select from arr and sum them.
for(var i=0; i<times; i++)
{
// Get a random integer number in the range [0, arr.length]
var index = Math.floor(Math.rand()*arr.length);

// check if the index we created has been selected again.
if(selectedIndex.indexOf(index)>-1)
{
// The created index has been selected again. So we must select another one,
// in order we get an item from the array only once.
while(selectedIndex.indexOf(index)>-1)
index = Math.floor(Math.rand()*arr.length);
}

// We push the created index in the selected index array.
selectedIndex.push(index);

// We increase the sum.
sum+=arr[index];
}
``````

update

In order the above to be executed the caller should provide a value for the variable called `times`. This value in order to be valid shouldn't exceed the length of the array called `arr`.

Another way more elegant, it would be to follow on this part the solution that deitch suggested in his post.

``````var times = Math.floor((Math.random() * arr.length)+1)
``````

The above should be placed just before the `for` statement.

### #2

1

``````I think you are looking something like:

<code>
function randormTotal() {
var arr = [1,2,3,4,5,6];
var total=0;
var noOfData = 3;
for(var i =0; i<noOfData; i++) {
var pos = Math.floor(Math.random()*(arr.length-1)) + 1;
total += arr[pos];
}
}
</code>
``````

### #3

0

FYI, this method actually modifies the array, so you might want to copy it.

``````// randomly select how many elements you will pick
var i, total = 0, elmsCount = Math.floor((Math.random() * arr.length)+1), current;
// select that many elements
for (i=0; i<elmsCount; i++) {
current = Math.floor(Math.random()*arr.length);
total += arr.splice(current,1)[0];
}
// total is now the sum
``````