简体   繁体   English

js:无法将参数传递给setTimeOut中的匿名函数

[英]js: unable to pass parameter to anonymous function in setTimeOut

I seem to be unable to pass parameter to an anonymous function as the argument of a setTimeOut call. 我似乎无法将参数传递给匿名函数作为setTimeOut调用的参数。 Here is the code 这是代码

http://jsfiddle.net/5xg5d6pp/ http://jsfiddle.net/5xg5d6pp/

var arr = ["Just a test","I miss you so much darling #$%&%@;..\]]/"];

console.log(arr);
for(var c=0; c < arr.length; c++){
    console.log(arr[c]);

    //wait 1 sec for next loop
    setTimeout(function(arr[c]) {
        do_magic(arr[c]);
    }, 1000);
}

function do_magic (passed_var){
    console.log(passed_var);
}

When you do this setTimeout(function(arr[c]) { You are defining a new function and saying that I want this function to accept a parameter called 'arr[c]', you aren't saying that you want to pass arr[c] to it and because you can't have any special characters in the name of a parameter you get an error. What you should do is define a function outside of the loop to avoid the loop closure issue and pass the parameter to that letting that function create the setTimeout for you. Please see JavaScript closure inside loops – simple practical example for more information about closures. Also read this to learn more about javascript functions: http://javascript.info/tutorial/functions-declarations-and-expressions 当您执行此setTimeout(function(arr[c]) {您正在定义一个新函数,并说我希望此函数接受名为“ arr [c]”的参数,这并不是说您要传递arr [c]并由于参数名称中不能包含任何特殊字符而导致错误,您应该做的是在循环外部定义一个函数以避免循环闭合问题并将参数传递给该函数让该函数为您创建setTimeout。请参阅循环内的JavaScript闭包-有关闭包的更多信息的简单实际示例 ,还请阅读此书以了解有关javascript函数的更多信息: http : //javascript.info/tutorial/functions-declarations-and -expressions

This is the correct code below: 这是下面的正确代码:

var arr = ["Just a test","I miss you so much darling #$%&%@;..\]]/"];

console.log(arr);
for(var c=0; c < arr.length; c++){
    console.log(arr[c]);

    setTimeoutFactory(arr[c]);
}

function do_magic (passed_var){
    console.log(passed_var);
}

function setTimeoutFactory(text) {
setTimeout(function() {
        do_magic(text);
    }, 1000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM