这是我的代码:
平均成绩
功能dosomething { var i = Number; var numbers = new Array {a,b,c}; 数字[0] = a; 数字[1] = b; 数字[2] = c; var total = 0; for(i = 0; i
</head>
<body>
<p id= "functionOutput"></p>
<input type="text" id="input" />
<input type= "button" id="enter" onclick="dosomething(input.value)"
value="Calculate" />
</body>
</html>
答案 0 :(得分:0)
要做到这一点,你需要做两件事:
var calculate_btn = document.getElementById('enter'),
input_field = document.getElementById('input'),
all_values = [];
// store input value to array when button is clicked
calculate_btn.addEventListener('click', function(){
var input_value = parseFloat( input_field.value );
// ensure it is a number
if( isNaN( input_value ) ) return;
all_values.push( input_value );
});
function get_input_value_average(){
// calculate new average
var total = 0,
average;
all_values.forEach( function( entry ){
total += entry;
});
average = total / all_values.length;
return average;
}
将此脚本标记放在</body>
标记之前:
<script>
var calculate_btn = document.getElementById('enter'),
input_field = document.getElementById('input'),
all_values = [];
// store input value to array when button is clicked
calculate_btn.addEventListener('click', function(){
var input_value = parseFloat( input_field.value );
// ensure it is a number
if( isNaN( input_value ) ) return;
all_values.push( input_value );
var input_average = get_input_value_average();
alert( 'average: ' + input_average + ' | entries: ' + all_values.join( ', ' ) );
});
function get_input_value_average(){
// calculate new average
var total = 0,
average;
all_values.forEach( function( entry ){
total += entry;
});
average = total / all_values.length;
return average;
}
</script>
应该这样做。