繁体   English   中英

JavaScript无法从函数的数组参数获取值

[英]JavaScript can't get value off function's array parameter

我试图根据其高度在列中订购一些图像,我有以下代码。 问题是,即使imgHeights.length正常工作,imgHeights [i](在redrawThumbs函数中)也不会返回值。 我究竟做错了什么? 谢谢=)

function redrawThumbs(imgHeights){
  // some irrelevant code here

  // initialise an array that will hold all the column's heights
  var colHeights = new Array(cols);
  for(a=0; a <= colHeights.length - 1; ++a){
    colHeights[a] = 0;
  }

  // take each image's height and add it to the shortest column
  for(i=0; i <= imgHeights.length - 1; ++i){
    var shortestCol = 0;

    for(c=0; c <= colHeights.length - 2; ++c){
      if(colHeights[c+1] < colHeights[c]){
        shortestCol = colHeights[c+1];
      }
    }

    alert("imgHeights[" + i + "] " + imgHeights[i]);

    colHeights[shortestCol] += imgHeights[i];
  }
}

// make an array of image heights
var imgHeights = new Array(totalThumbs);    
for(i=1; i <= totalThumbs; ++i){
  var img = new Image();
  img.onload = function(){
  imgHeights[i-1] = this.height;
}
img.src = i + ".jpg";

// call function that orders the images
redrawThumbs(imgHeights);

问题之一是i变量是通过引用而不是通过值捕获的,因此,对于img.onload所有回调都获得了相同的i值。 考虑将onload分配更改为

var loadedCount = 0;
img.onload = (function (i) { 
    return function () { 
        imgHeights[i - 1] = this.height;
        if (++loadedCount == totalThumbs) allLoaded();
    };
})(i);

function allLoaded() {
    // called after all the images have been loaded.
}

这将在自动执行函数执行时捕获i值的副本,并在加载所有图像后调用allLoaded()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM