以下是我的学校项目的代码(使用Murach的Ray Harris的Murach JavaScript和DOM脚本)。本章仅约数组,不包括原型,但我想尝试一下基于Internet的教程和参考:JavaScript关联数组访问返回“literal”数组原型代码
/*
Operation
This application stores the last name, first name, and score for
one or more students and it calculates the average score for all of the scores
that have been entered. When the user clicks on the Clear button, this
application clears the score data from this application. When the user clicks
on the Sort button, this application sorts the data in alphabetical order by
last name.
Specifications
The program should use one or more arrays to store the data.
Assume that the user will enter valid data.
*/
var $ = function (id)
{
return document.getElementById(id);
}
/*
Array prototype object extension for averaging the contents
"Adding a method to the built-in Array object to extract the average
of any numerical values stored in the array is therefore a useful
addition to that object." http://javascript.about.com/library/blaravg.htm
*/
Array.prototype.average = function()
{
var avg = 0;
var count = 0;
for (var i = 0; i<this.length; i++)
{
//never gets here:
alert(i + ": " + this[i]);
var e = +this[i];
if(!e && this[i] !== 0 && this[i] !== '0')
{
e--;
}
if (this[i] == e)
{
avg += e;
count++;
}
}
return avg/count;
}
var addScore = function()
{
studentScores[$('last_name').value + ', ' + $('first_name').value] = $('score').value;
update();
}
var clearScore = function()
{
for (var i in studentScores)
{
studentScores[i] = '';
}
update();
}
var sortScore = function()
{
scores.sort();
update();
}
var update = function()
{
var result = '';
for (var i in studentScores)
{
result += (i + ': ' + studentScores[i] + '\n');
}
$('scores').value = result;
$('average_score').value = studentScores.average().toFixed(1);
}
window.onload = function()
{
//a variable is initialized inside a function without var, it will have a global scope:
studentScores = [];
$('add_button').onclick = addScore;
$('sort_button').onclick = sortScore;
$('clear_button').onclick = clearScore;
$('last_name').focus();
}
当代码进入“更新()”功能(“addScore结束()“函数)并访问数组, 它将原型中的”文字“代码填充到文本区域中(并且未能在下一行中找到平均值):
我没有足够的重新点发布图像,但这里是我的输出(在Chrome JS控制台中没有错误):
lowe, doug: 82
average: function()
{
var avg = 0;
var count = 0;
for (var i = 0; i<this.length; i++)
{
//never gets here:
alert(i + ": " + this[i]);
var e = +this[i];
if(!e && this[i] !== 0 && this[i] !== '0')
{
e--;
}
if (this[i] == e)
{
avg += e;
count++;
}
}
return avg/count;
}
任何帮助赞赏(最佳做法或算法建议欢迎)
你什么时候实际调用'output'? – 2013-02-16 19:43:02
什么'output()'函数,什么数组? – melpomene 2013-02-16 19:44:49
哎呀......“update()”函数就是我的意思,编辑 – PAINKILLER 2013-02-16 20:19:56