gpt4 book ai didi

javascript - 不工作,如何将随机变量推送到数组并输出数组 Javascript 的总计

转载 作者:行者123 更新时间:2023-11-30 23:56:00 24 4
gpt4 key购买 nike

第一个函数产生一个随机数。每次调用第二个函数时,它都应该输出加在一起的数组值的总数。为什么这只输出一个变量值?

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com