Ad

Strange Closure Issue In Javascript

- 1 answer

How come in my case I was getting ['undefined1','undefined2'] value for my array? I pushed it in the same scope.

router.post('/add', function(req, res) {
    var imageArr = [];
    for(var i = 1; i <= 4; i++) {
        if (req.body["photo" + i]) {
            imageArr.push(req.body.photo + '' + i);
        }
    }

    console.log(imageArr) // working fine here, returning correct values like ['something','something']

    if (req.body.is_update) {
        console.log(imageArr) // working fine here too, returning correct values
    } else {
        console.log(imageArr) // not working fine here, returning undefined1, undefined2.. 
    }
}

Is it because of async, possibly?

Ad

Answer

I thought I would turn my comment into a formal answer to this question so it won't hang unanswered.

You need to replace this part of you script imageArr.push(req.body.photo+''+i); with imageArr.push(req.body["photo"+i]);. Examples of console outputs for both cases can be seen in this fiddle.

Ad
source: stackoverflow.com
Ad