我想根據其高度對列中的某些圖像進行排序,並且我有以下代碼。 問題是即使imgHeights.length工作正常,imgHeights [i](在redrawThumbs函數中)不會返回值。 我做錯了什麼?感謝=)JavaScript無法從函數的數組參數中獲取值
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);
您可能想要在代碼中添加縮進,並添加缺少的}。很難判斷你的'redrawThumbs()'方法在哪裏結束。 – jaredhoyt
我加了缺少的}。 indentation ... 2空間不是那樣的小代碼不好:D 我剛纔注意到最怪異的事情,而調試是底部爲我在哪裏創建imgHeights陣列,以及我把一個警報在那裏打印我的變量和它總是顯示循環的最後一個數字。我不知道爲什麼會發生這種情況,因爲它使用它創建元素時工作正常 –