0

これが私の学校プロジェクトのこれまでのコードです(MurachのJavaScriptとRay HarrisによるDOMスクリプティングを使用)。この章はアレイに関するものであり、プロトタイプについては説明していませんが、インターネットのチュートリアルとリファレンスに基づいて試してみたかったのです。

 /*
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();
}

コードが「update()」関数(「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;
}

助けていただければ幸いです(ベストプラクティスまたはアルゴリズムの提案を歓迎します)

4

3 に答える 3

1

それは簡単です: Array のループに列挙型を使用しないでくださいfor…in! clearScoreand関数でこれを行いupdateます。

for (var prop in obj)継承されたものを含むすべての [列挙可能な] プロパティをループしますArray.prototype(少なくとも Array オブジェクトの場合)。ループにはそのfor (var i=0; i<array.length; i++)問題はありません。

于 2013-02-16T19:48:58.993 に答える
1

これを変える:

studentScores = []

これに:

studentScores = {}

...アレイの代わりにオブジェクトを使用しているように。

ループforインaverage()は、作成した非数値キーではなく、数値インデックスを反復しているだけです。

average()他のメソッドと同様にスタンドアロン関数としてメソッドを作成し、それに渡しstudentScoresて平均を計算し、for-in代わりに を使用しforます。

于 2013-02-16T20:09:43.520 に答える
0

studentScores を配列にするか (つまり、格納されたデータにアクセスするために整数を使用する)、またはオブジェクト/連想配列 (要素の設定/取得に文字列を使用する) にするかを決定する必要があります。

学生の名前をキーとして使用する場合は、studentScores をオブジェクトとして宣言する必要があり、「average」メソッドを Object プロトタイプに追加する必要があります (これはお勧めしません)。

コードの現在の状態で、Array もオブジェクトであり、他のオブジェクトと同様に任意のプロパティをアタッチできるという事実に出くわしました。名前でプロパティを追加しましたが、平均的な方法では、数値ベースのインデックスにアクセスしようとしています。ただし、追加するデータが保存される場所ではありません。

> a = [];
[]
> a['foo'] = 'bar';
'bar'
> a.length
0
> a[3] = 0;
0
> a.length
4
于 2013-02-16T19:54:32.877 に答える