Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through an array

Trying to do simple js and not sure where im going wrong, trying to make a link for each array item

app.get('/list', function(req, res){
    fs.readdir(__dirname + "/files", function (err, files) {
        if (err) throw err;

         var items = ["a", "b", "c"]; //using items opposed to files for demostration
         for( var i=0;i<items.length;i++){
             res.send('<a href="#">'+items[i]+'</a>');
         } 
    }); 
});

and its just returning the first item as a link, is there something different that I should be doing with nodejs?


1 Answers

Build the links, and then send them all, like this:

fs.readdir(__dirname + "/files", function (err, files) {
    var items, links;
    if (err) throw err;

    items = ["a", "b", "c"];
    links = '';
    items.forEach(function(item) { // native array foreach.
        links += '<a href="#">' + item + '</a>';
    });

    res.send(links);
}); 
like image 188
Stephen Avatar answered May 03 '26 02:05

Stephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!