我在使用setTimeout函數內部的參數調用函數時遇到問題。基本上我試圖做一個小型的在線遊戲,在那裏我創建一個命令隊列,然後一次執行一個(每個都需要一些時間來顯示可視化)。作爲setTimeout()中的參數傳遞時,變量會丟失()
不幸的是,我似乎無法在setTimeout()中傳遞任何變量作爲參數。雖然當我調用該函數時,該變量確實存在,但它在執行後不存在。該函數不會跟蹤傳遞的值。
有沒有解決這個問題的方法?非常感謝您的幫助。下面是一個代碼我使用:
function executeCommands() {
var commands = document.getElementsByClassName("cmdplace");
var timeout = 0;
for (i = 0; i < commands.length; i++) {
console.log(commands[i].childNodes[0]); //variable exists
setTimeout(function() {go(commands[i].childNodes[0]);}, timeout+=400); //Uncaught TypeError: Cannot read property 'childNodes' of undefined
console.log(commands[i].childNodes[0]); //variable still exists
}
}
function go(command) {
//do somethig based on the passed command
}
什麼去()?.. – baao
啊,對不起。 go()是我的函數,它根據傳遞的命令執行某些操作。 –
@PetrHofman,你可以看到下面 – Aruna