我聲明變量,函數以外,像這樣:的Javascript全局數組與jquery .push在替代函數返回空數組
var vitalsValuesChecked = [];
則功能的內部我做的:
vitalsValuesChecked.push('foobar');
在後面的函數中,我需要遍歷數組來推送項目,並且始終沒有得到我期望的結果。所以在同樣的功能裏,我添加了console.log(vitalsValuesChecked);
,它返回[]
。
編輯下面的代碼示例; 編輯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]);
}
}
你能告訴我們這個函數,或者它的最小版本來重現這個問題嗎? – 2012-08-10 21:13:41
如果你發佈你的代碼,這將有所幫助。 – 2012-08-10 21:14:19
您必須向我們展示導致問題的ACTUAL代碼,因爲'.push()'沒有任何問題。 – jfriend00 2012-08-10 21:19:32