以下是我的學校項目的代碼(使用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