setTimeout在for循环中传递参数

Her*_*mes 2 javascript closures settimeout angularjs

我创建了一个数组。我想用settimeout发送ajax请求。但是我无法在settimeout中获取参数。当我打印控制台日志变量时,我是不确定的。我怎么解决这个问题?

控制台日志结果

i undefined
Run Code Online (Sandbox Code Playgroud)

JavaScript代码

$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);
        $scope.params = {
            lat: $scope.lat,
            lng: $scope.lng,
            time: $scope.time,
            type: $scope.type[i]
        }
        console.log("params", $scope.params);
        return;
        $.ajax({
            type: 'post',
            url: "bz.php",
            dataType: 'json',
            async: true,
            cache: false,
            data: $scope.params,
            success: function (data) {
                if (data.response) {
                    console.log("data.response", data.response);
                    return;
                    if (!$scope.$$phase) $scope.$apply();
                } else if (data.response == null) {

                } else if (data.error) {

                }
            },
            error: function (data) {
            }
        });
    }.bind(this), i * 2000);
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*lms 5

将i添加为setTimeout的第三个参数以对其进行封装:

setTimeout(function(i){ // <--  ... and retrieved here again
   console.log(i);
}, i * 2000, i);// <--- i is stored here ...
Run Code Online (Sandbox Code Playgroud)


小智 5

你不需要.bind(). 使用letconst代替var...

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (let i = 0; i < $scope.type.length; i++) {
    setTimeout(function () {
        console.log("i", i);

        // your code

    }, i * 2000);
}
Run Code Online (Sandbox Code Playgroud)

或者只是i作为附加参数传递给setTimeout.

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);

        // your code

    }, i * 2000, i);
}
Run Code Online (Sandbox Code Playgroud)