简体   繁体   中英

Generate an array of javascript functions from a for loop

I am having some issues with an array of functions. When I run the code below it adds the function to the array but it doesnt change the value of index inside the function. Any help would be greatly appreciated. Thanks

var dlinks = [];
function getLinks(index) {
    return function() {
        this.echo('report link September');
        casper.start(reportList[index]);
        casper.thenOpen(reportList[index], function() {
            casper.capture('data1.png');
            var dlUrl = reportList[index] + '&csv=true';
            this.download(dlUrl , reportDates[index].substring(0,2) + myfile, "GET");
        });
    }
}
console.log(getLinks(1));
for (var i = 0; i < reportList.length; i ++) {
        dlinks.push(getLinks(i));
}

You have some slight syntax errors.

var dlinks = [];
function getLinks(index) {
    return function() {
        return index;
    };
}
for (var i = 0; i < 10; i ++) {
    dlinks.push(getLinks(i));
    $("body").append(getLinks(i));
}

$("body").append("Test");

http://jsfiddle.net/HFXrm/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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