第一个函数产生一个随机数。每次调用第二个函数时,它都应该输出加在一起的数组值的总数。为什么这只输出一个变量值?
function random() {
return Math.floor((Math.random() * 10) + 1);
}
var addtime = [];
function totalArray() {
var newCell3 = random();
var Value = '';
var total = 0;
value = newCell3;
addtime.push(value);
for (var i in addtime) {
total += addtime[i];
}
console.log(total);
}
totalArray();
最佳答案
我想这就是您正在寻找的:
const random = () => Math.floor((Math.random() * 10) + 1);
var addTime = [];
document.getElementById('button').addEventListener('click', totalArray);
function totalArray() {
const newValue = random();
let total;
addTime.push(newValue);
total = addTime.reduce((x, y) => x + y, 0);
console.log(total);
}
<button id="button">Click Me!</button>
关于javascript - 不工作,如何将随机变量推送到数组并输出数组 Javascript 的总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61046704/