简体   繁体   中英

Strange closure issue in javascript

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?

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.

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