2013-02-16 57 views
0

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

任何幫助讚賞(最佳做法或算法建議歡迎)

+0

你什麼時候實際調用'output'? – 2013-02-16 19:43:02

+0

什麼'output()'函數,什麼數組? – melpomene 2013-02-16 19:44:49

+0

哎呀......「update()」函數就是我的意思,編輯 – PAINKILLER 2013-02-16 20:19:56

回答

1

更改此:

studentScores = [] 

這樣:

studentScores = {} 

...讓你使用一個對象而不是數組。

您的for循環average()只是迭代數字索引而不是您創建的非數字鍵。

創建average()方法和別人一樣一個獨立的功能,並通過studentScores它來計算平均值,然後用for-in,而不是for

+0

您確切知道我要做什麼並解決了您的解決方案 - 謝謝! – PAINKILLER 2013-02-16 20:44:30

+0

@Humanodude:不客氣。 – 2013-02-16 20:46:07

1

這很簡單:Do not use for…in enumerations for looping Arrays!您在clearScoreupdate函數中這樣做。

for (var prop in obj)遍歷所有[enumerable]屬性,包括那些從Array.prototype(至少對於Array對象)繼承的屬性。 A for (var i=0; i<array.length; i++)循環不會有這個問題。

+0

好的建議,謝謝。我結束了與'去... ...因爲我想要使用關聯數組(正確) – PAINKILLER 2013-02-16 20:47:38

0

您必須決定是否打算將studentScores作爲數組(即用於存取數據的整數)或對象/關聯數組(用於設置/獲取元素的字符串)。

如果你想使用學生的名字作爲鍵,你應該聲明studentScores爲一個對象,你的'平均'方法將被添加到對象原型(我不建議)。

隨着代碼的當前狀態,你已經偶然發現數組也是一個對象,並且可以像任何其他對象一樣附加任意屬性。您已經按名稱添加了屬性,但在您的平均方法中,您嘗試訪問基於數字的索引。但這並不是您要添加的數據存儲在哪裏。

> a = []; 
[] 
> a['foo'] = 'bar'; 
'bar' 
> a.length 
0 
> a[3] = 0; 
0 
> a.length 
4 
+0

「對象/關聯數組」 - 感謝您對對象與數組索引的幫助解釋,並帶有示例 – PAINKILLER 2013-02-16 20:46:19