如何在任意范围内随机选择数字并使用JavaScript数组将其相加
我正在尝试编写一些JavaScript,它将从数组中选择一些随机数,然后将这些随机数相加,形成一个总值 例如,如果我有如何在任意范围内随机选择数字并使用JavaScript数组将其相加,javascript,arrays,random,Javascript,Arrays,Random,我正在尝试编写一些JavaScript,它将从数组中选择一些随机数,然后将这些随机数相加,形成一个总值 例如,如果我有var array=[1,22,5,88,3,105,7,88,987]我希望代码随机选择它想要的数字(每次运行时选择的数量都会发生变化),然后将它们相加,但我不确定这是否可行 我是JavaScript新手,所以我只编写了将所有数组元素添加到一起的代码,而不是随机选择 var arr = [1,2,3,4,5,6]; var total=0; for(var i in a
var array=[1,22,5,88,3,105,7,88,987]
我希望代码随机选择它想要的数字(每次运行时选择的数量都会发生变化),然后将它们相加,但我不确定这是否可行
我是JavaScript新手,所以我只编写了将所有数组元素添加到一起的代码,而不是随机选择
var arr = [1,2,3,4,5,6];
var total=0;
for(var i in arr) { total += arr[i]; }
我的代码非常基本,所以请原谅我,我还在学习。谢谢您可以使用
Math.rand()
函数来创建随机索引。在代码方面:
// 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];
}
上述内容应放在for
语句的前面。我认为您看起来像:
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];
}
alert(total);
}
</code>
函数randormTotal(){
var-arr=[1,2,3,4,5,6];
var合计=0;
var noOfData=3;
对于(var i=0;iFYI),此方法实际上会修改数组,因此您可能需要复制它
// 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
//随机选择要拾取的元素数量
变量i,总计=0,elmscont=Math.floor((Math.random()*arr.length)+1),当前;
//选择那么多元素
对于(i=0;我这里介绍了如何获取一个随机元素,只需在每次需要时进行操作并每次添加结果。是的,我也喜欢这个。只要确保不选择同一元素两次,就可以了。我将对此进行投票。@deitch感谢dude!谢谢你:)当我运行代码时,它总是告诉我时间没有定义任何想法?我在使用TextPad(不是我的选择)@user2982634欢迎你,伙计!你必须为times
变量提供一个值。哦,那么我只需输入任何数字而不是单词times?
// 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