1

テーブルをループして(最初は非表示)、要求されたセクションに応じて特定の行を表示するために使用される配列を作成しました。

var rows_per_section = [ {min: 0, max: 7}, {min: 7, max: 17}, {min: 17, max: 21}, {min: 21, max: 35}, {min: 35, max: 41}, {min: 41, max: 46}, {min: 46, max: 52},{min: 52, max: 56} ];
var rows_min = rows_per_section[section_no].min;
var rows_max = rows_per_section[section_no].max;

テーブルの長さを変えることができるため、テーブルを循環し、rows_per_section 配列を独自に作成する追加の関数を使用して、スクリプトを変更しようとしています。クラスタグを探すことでテーブルのブレークを検出できますが、ブレークに達するたびに配列を作成して新しい値を追加する方法がわかりません。

function create_section_array(profile_table, no_of_sections) {
    var section_counter = 0;
    var rows_per_section = new Array();    //this is where it starts to go wrong
                                           //need to create the array and stick in the
                                           //MIN value for the first section as 0
    for (i=0;i<profile_table.length-1;i++) {
        var table_row = profile_table.item(i);
        var row_content = table_row.getElementsByTagName("td");
        if(row_content[0].className == "ProfileFormTitle") {
            if(section_counter != 0) {
                //if not the first section add a MAX value to
                //rows_per_section[section_counter + 1]
            }
            if(section_counter != no_of_sections) {
                //if not the last section add a MIN value to
                //rows_per_section[section_counter]
            }
            section_counter++;
        }
    }
    return rows_per_section;
}
4

1 に答える 1

0

関数を次のように変更します。

function create_section_array (profile_table, no_of_sections) {
    var section_counter = 0,
        rows_per_section = [ { min: 0 } ],
        precedingLength = 0,
        i, row_content;

    for (i = 0; i < profile_table.length; i += 1) {
        row_content = profile_table[i].getElementsByTagName('td');

        if (row_content[0].className === 'ProfileFormTitle') {
            if (section_counter !== 0) {
                rows_per_section[section_counter] = {
                    max: row_content.length - 1
                };
            }

            if (section_counter !== no_of_sections) {
                rows_per_section[section_counter].min = precedingLength;
            }

            section_counter += 1;
            precedingLength += row_content.length;
        }
    }

    return rows_per_section;
}

上記に関するいくつかの注意事項:

  • iは最初は明示的に宣言されていませんでした。つまり、グローバルに存在していました。宣言を追加しました。

  • JavaScript にはブロック スコープはなく、関数スコープ ( vars は巻き上げられます) のみです。の宣言をrow_content関数の先頭に移動しました。これが一般的な慣用的なスタイルであるためです。

  • 演算子==!= は型強制を実行します。一般に、代わりに===andに固執する方が安全です。!==

  • 配列はリテラル構文で宣言できます。. は必要ありませんnew Array()。あなたの場合、[ { min: 0 } ]基本的な必要な構造を設定するために使用して初期化しますが、より一般的には、人々が空の配列で初期化するのを見ます[].

  • 同様に、配列に新しいインデックスの値を設定する場合、必要な基本構造にリテラル オブジェクト構文を使用できます。あなたの場合、これは{ max: row_content.length - 1 }.

  • 技術的には、これは多次元配列ではなく、オブジェクト (または辞書、マップ、キー/値ストアなど、呼びたいもの) の配列です。

  • 私は実際に上記を実行しておらず、問題の文脈について漠然とした感覚しか持っていません。このコードには問題があるかもしれません (おそらく?)。:)

于 2013-01-24T11:41:04.560 に答える