0

次のように、関数の外側で変数を宣言します。

var vitalsValuesChecked = [];

次に、関数内で次のことを行います。

vitalsValuesChecked.push('foobar');

後の関数では、プッシュされたアイテムの配列をループする必要があり、常に期待する結果が得られません。その同じ関数内に、console.log(vitalsValuesChecked);which returnsを追加しました[]

以下のコードサンプルを 編集します。編集2以下の修正コード

var vitalsValuesChecked = [];

$(document).delegate("#hv-byresult-btn", "click", function () {
    var vitalsTypeList = ['bp', 'ht', 'wt', 'pulse', 'resp', 'temp'];
    vitalsValuesChecked = [];
    for (var i = 0;i < vitalsTypeList.length;i++) {
        if (document.getElementById(vitalsTypeList[i]).checked == true) {
            vitalsValuesChecked.push(vitalsTypeList[i]);
            console.log(vitalsTypeList[i] + " is checked. Adding to global array");
        }
    }
    $('#vitals-measures-content').empty();
    navigate("#vitals-measures");
    for (var i = 0;i < vitalsValuesChecked.length;i++) {
        console.log("vitalsValuesChecked at index " + i + " is " + vitalsValuesChecked[i]);
     }
        readRec('clinicalObservation', null, sortVitalsByResult);

    });
function foobar() {
    console.log(vitalsValuesChecked); //return []
    for (var i=0;i < vitalsValuesChecked.length;i++) {
        var valueSelected = vitalsValuesChecked[i];
        console.log("Value of vitalsValuesChecked at index " + i + " is " + vitalsValuesChecked[i]);
    }
}
4

2 に答える 2

2

You have defined vitalsValuesChecked twice which is a problem. One is global and one is local to the delegate() callback. The local definition overrides the global definition so when you thought you were setting values into the global variable, you were not - you were just changing the local variable which has a limited lifetime and thus your data was not available later in the global variable.

You should remove the

var vitalsValuesChecked = [];

inside the delegate handler so all modifications occur on the single global variable.

于 2012-08-10T21:19:55.187 に答える
1

関数内でvar vitalsValuesChecked = [];ローカル変数を作成します。グローバル変数にプッシュしようとしている場合、これは必要ないと思います。

于 2012-08-10T21:21:23.593 に答える