2016-01-02 86 views
0

我想將隨機數添加到數組中,該數組被分配給一個將數字加在一起的函數。如何將變量的值添加到數組函數?

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; 
    } 

} 
+0

好...參數'number'從未在功能,'value.value'是不確定的使用,一個號碼沒有一個所謂的價值屬性,值不有.push方法,因爲它不是Array ...這只是代碼的第1,2和3行 - 第3行會在開發人員工具控制檯中產生錯誤... –

+0

和第5行總是會導致myArray值爲0 –

回答

1

UPDATE

重讀這個問題,並確定累計總數期望所以這個演示將:

  • 生成的隨機數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>



OLD

該陣列在此演示預定var xArray = [23, 8, 90, 7];

function randomNumber(xArray){ 
 
    var value = Math.floor(Math.random() * 10) + 1 ; 
 
    xArray.push(value); 
 
\t \t 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>