我試圖運行一個FOR循環,其中需要在另一個函數中再次運行的變量,我需要將它們編碼出第一個函數 但函數receive他們爲「未定義」。無法在函數內傳遞全局變量
當變量在collectionChecking函數中除了ledTypes2以外的局部變量時,handleResponse2的函數試圖調用它時,hostIndx2的變量未定義。此函數應該將響應呈現爲HTML頁面內ledTypes2方法的圖標。
var fetch = require('node-fetch');
var ledTypes = {
green: "<img id='logo' src='green.png' height='30' width='30'>",
red: "<img id='logo' src='red.png' height='30' width='30'>",
yellow: "<img id='logo' src='yellow.png' height='30' width='30'>"
};
var hosts2 = ['http://host1.com','host2.com','host3.com','host4.com'];
var hostIndx2 = 0;
var lengthVal = hosts2.length;
var token = '1213232431';
function collectionChecking() {
console.log("im inside the func" + hostIndx2 + "---" + lengthVal);
for (; hostIndx2 < lengthVal; hostIndx2++) {
console.log(hostIndx2);
let url = hosts2[hostIndx2];
// sendReq();
fetch(url , {method: 'GET', headers:{"X-AUTH-TOKEN": token, "Content-Type": "text/plain"}, timeout: 30000}
).then(function (res, hostIndx2) {
console.log(res.status, hostIndx2);
handleLedResponse2(res, hostIndx2);
});
}
}
function handleLedResponse2(res, hostIndx2) {
var curSpan = document.getElementById('col_host_' + hostIndx2);
console.log("IM HERE" + res.status + "---" + hostIndx2);
if (res.status === 200 || res.status === 204) {
curSpan.innerHTML = ledTypes.green;
} else if (res.status === 500 || res.status === 404) {
curSpan.innerHTML = ledTypes.red;
} else if (res.status === 300 || res.status === 301 || res.status === 302) {
curSpan.innerHTML = ledTypes.yellow;
}
}
請更具體地說明您遇到的問題。哪些確切的變量是未定義的,哪些代碼行?而且,「需要將它們編碼出第一個函數」是什麼意思?請更確切地說明您的問題以及您想要達到的目標。 – jfriend00
謝謝,當handleResponse2的函數試圖調用他時,hostIndx2的變量是未定義的。此函數應該將響應呈現爲HTML頁面內ledTypes2方法的圖標。 –