gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:53:48 25 4
gpt4 key购买 nike

我正在尝试根据图像的高度对列中的一些图像进行排序,并且我有以下代码。问题是,尽管 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 的所有回调都获取相同的值。考虑将 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()

关于JavaScript 无法从函数的数组参数获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10457118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com