处理JavaScript中的循环,只有最后一项会受到影响? [英] dealing with loops in javascript, only last item gets affected?

查看:66
本文介绍了处理JavaScript中的循环,只有最后一项会受到影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用用于处理图像操作的gm npm模块。并且我有此代码。

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.

推荐答案

将代码更改为:

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);
}

否则 i 将为3。

这篇关于处理JavaScript中的循环,只有最后一项会受到影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆