gpt4 book ai didi

javascript - 如何将变量的值添加到数组函数?

转载 作者:行者123 更新时间:2023-12-03 08:01:29 26 4
gpt4 key购买 nike

我正在尝试将随机数添加到数组中,该数组分配给一个不断将数字相加的函数。

function getMiNumber(number){
var value = Math.floor(Math.random() * 10) + 1 ;
value.push(value.value);

var myArray = someCalc([0]);
console.log(myArray);
function showMe(val) {
var presentMe = document.getElementById('someId');
presentMe.innerHTML = val;
}
showMe(myArray);

function someCalc(list) {
var total = 0;
for(var i = 0; i < list.length; i++){
total += list[i];
}
return total;
}

}

最佳答案

更新

重新阅读问题并确定需要累积总数,因此此演示将:

  • 生成 1 到 10 之间的随机数。
    • 显示该数字。
  • 将该数字添加到数组中。
    • 显示该数组。
  • 添加数组的所有元素。
    • 显示总数。

<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>34562147</title>
<style>
html,
body {
font: small-caps 400 16px/1.4 'Source Code Pro';
}
fieldset {
border: 2px inset grey;
border-radius: 10px;
}
legend {
font-size: 1.3rem;
}
</style>
</head>

<body>
<fieldset>
<legend>Random Array Total</legend>
<input id="btn1" type="button" onclick="rand()" value="Random" />
<br/>
<label for="out0">Next:
<output id="out0"></output>
</label>
<br/>
<label for="out1">Array:
<output id="out1"></output>
</label>
<br/>
<label for="out2">Total:
<output id="out2"></output>
</label>
</fieldset>
<script>
var xArray = [];

function rand() {
var ran1 = Math.floor(Math.random() * 10) + 1;
var out0 = document.getElementById('out0');
var out1 = document.getElementById('out1');
var out2 = document.getElementById('out2');
out0.value = ran1;
xArray.push(ran1);
out1.value = xArray;
out2.value = calc(xArray);
}

function calc(xArray) {
var total = 0;
for (var i = 0; i < xArray.length; i++) {
total += xArray[i];
}
return total;
}
</script>
</body>

</html>

<小时/><小时/>

本演示中预先确定了数组 var xArray = [23, 8, 90, 7];

function randomNumber(xArray){
var value = Math.floor(Math.random() * 10) + 1 ;
xArray.push(value);
return xArray;
}
var xArray = [23, 8, 90, 7];
var total = calc(randomNumber(xArray));
console.log(total);
function output(total) {
var out1 = document.getElementById('out1');
out1.value = total;
}


function calc(list) {
var total = 0;
for(var i = 0; i < list.length; i++){
total += list[i];
}
return total;
}

output(total);
<output id="out1"></output>

关于javascript - 如何将变量的值添加到数组函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562147/

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