0

我正在创建一个这样的函数数组。数组中的url是正确的,但是当我最终循环遍历数组列表中的这些信息时...... x[1]处的函数引用了存储到url中的最后一个值,同时x[0]是正确的。有没有办法调整内部url以匹配x[0]?我正在考虑为 anon-function 设置一个参数,但我不确定这是否会起作用。我也不确定我是否可以在数据树上工作,就像 function.parent[0] 引用函数的父级并调用元素 0。我猜最后一个想法是用 DOM 逻辑方式思考。

var newArray = new Array();
    for(var i=0;i<fileUrls.length;++i) {
        var url = fileUrls[i];
        var x = [];//new Array();
        x = [url,
            function(){
                displayFile(url, 'image', null, ft_id, null, null, null, null, !MA.isiOS());
            }, 
            function(e){
                if(DEBUG) console.log('Error creating gallery thumbnail');
                alert('There was a problem creating a thumbnail');
                MA.hideMessage();
            }
        ];
        newArray.push(x);
    }
   pollingThrottler(2,newArray, function(a,b,c){ 
            //alert(a+"\n-----\n"+b+"\n-----\n"+c);
            //alert(bentleyPlugins.createThumbnailForPath(a,b,c));
            //alert(a);
                            //a does not reference the correct item.
            createThumbnailForPath(a,b,c);
            return;
        },function(){
            alert("success!");
        });

是实际的代码。

4

2 回答 2

2

您需要为数组元素创建一个生成器函数,如下所示:

function genElement( url ) {
 return [url,
  function(){
    displayFile(url, 'image', null, ft_id, null, null, null, null, !MA.isiOS());
  }, 
  function(e){
    if(DEBUG) console.log('Error creating gallery thumbnail');
    alert('There was a problem creating a thumbnail');
    MA.hideMessage();
  }
 ];
}    
arrayList.push( genElement( myUrl ) );

基本上,您的代码中发生的情况是,所有函数元素都将引用同一个url变量,该变量会在循环过程中更改其值。

当您使用生成器函数时,将在调用生成器函数时生成 url 的副本。这导致每个元素都有其“自己的” url 变量来引用。

编辑

但是,为了易于阅读代码和性能,我建议@dystroy 的答案,因为在我看来这是做这些事情的更好方法。

于 2012-09-28T13:39:42.910 回答
1

您不应该使用数组,而是使用面向对象的 javascript:

function Thing(url) {
    this.url = url;
}
Thing.prototype.display = function(){
 displayFile(this.url, 'image', null, ft_id, null, null, null, null, !MA.isiOS());
};
Thing.prototype.doSomething = function(){
   if(DEBUG) console.log('Error creating gallery thumbnail');
    alert('There was a problem creating a thumbnail');
    MA.hideMessage();
};

然后你可以打电话

arrayList.push(new Thing(url));

然后x.display()将使用正确的网址。

这是一本关于 javascript 中 OOP 的实用读物。

编辑 :

这是获取所需数组/对象的补充方法:

Thing.prototype.asArray = function(){
   var _this = this;
   return [this.url, function(){_this.display()}, this.doSomething];
}

但它开始不太清楚......

于 2012-09-28T13:40:10.227 回答