如何添加变量's值转换为数组函数

How to add a variable's value to an array function?

本文关键字:转换 函数 数组 何添加 添加 变量      更新时间:2023-09-26

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

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>