dealing with loops in javascript, only last item gets affected? [duplicate]

寵の児 提交于 2019-12-19 07:37:21

问题


Im working with the gm npm module that deals with image manipulation. and i have this code.

for(i=0;i < 4;i++){
    gm("www/img/" + image[i]).crop(550, 406, 0, 0).write(function(err) {
         console.log(this.outname + " created  ::  " + arguments[3]); //success
    });
}

this loop is meant to loop through the images array and crop each photo, but it only crops the last one. i think its something to do function invocation and callbacks, but not advanced yet for that level.


回答1:


Change your code to:

for (var i = 0; i < 4; i++) {
  (function (i) {
    gm("www/img/" + image[i]).crop(550, 406, 0, 0).write(function(err) {
         console.log(this.outname + " created  ::  " + arguments[3]); //success
    });
  }).call(this, i);
}

otherwise the value of i will be 3 each time your callback is being invoked.




回答2:


You need to create a "closure" over the variable

Js has a function scope.

for (i = 0; i < 4; i++)
{
    (function (a)
    {
        gm("www/img/" + image[a]).crop(550, 406, 0, 0).write(function (err)
        {
            console.log(this.outname + " created  ::  " + arguments[3]); //success
        });
    }).call(this,i)
}

or

that=this;

for (i = 0; i < 4; i++)
    {
        (function (a)
        {
            gm("www/img/" + image[a]).crop(550, 406, 0, 0).write(function (err)
            {
                console.log(that.outname + " created  ::  " + arguments[3]); //success
            });
        })(i)
    }

edit :

Also - I would also keep a reference to the arguments since now , after IIFE - the arguments is changing.

you can keep your arguments via :

var args= Array.prototype.slice.apply(arguments)

example :

function g()

{
for (i = 0; i < 4; i++)
    {
        (function (a)
        {
           console.log(arguments); //huh ? arguments are not a,b,c !!! anymore
        })(i);
    }
}


g('a','b','c') // 0,1,2,3

so you do need to keep reference to the arguments cuz their changed after IIFE.



来源:https://stackoverflow.com/questions/22438002/dealing-with-loops-in-javascript-only-last-item-gets-affected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!