I declare a variable, outside of a function like so:
var vitalsValuesChecked = [];
then inside of a function I do:
vitalsValuesChecked.push('foobar');
In a later function I need to loop through the array for the items pushed, and constantly am not getting the result I expect. So inside that same function, I added console.log(vitalsValuesChecked); which returns [].
EDIT Code sample below;
EDIT 2 Fixed code below
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]);
}
}
You have defined
vitalsValuesCheckedtwice 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
inside the delegate handler so all modifications occur on the single global variable.