下面的代碼基本上遍歷掉落的文件,將文件對象壓入filesArray並將文件附加到DOM,如果它們符合標準(小於1mb並且是png/jpg /圖)。我已將允許的fileSize設置爲1MB。數組長度不等於數組對象
for (var i = 0, f; f = files[i]; i++) {
if (validateType(files[i].type)){
//alert("ok");
if (files[i].size < allowedSize){
filesArray[i]=files[i];
var reader = new FileReader();
a = 0;
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result;
//image.width = 100; // a fake resize
imageBoxWrapper = $("<span />", {id: "idw"+a,class: "imageBoxWrapper"});
imageBox = $("<span />", {id: "idb"+a,class: "imageBox"});
complete = imageBox.append(image);
$(complete).appendTo(imageBoxWrapper);
newimageBox = $(imageBoxWrapper).append("<span class='imageDelete' imageIndex="+a+"><img src='images/icons/cross.png'> Delete</span>");
$(newimageBox).appendTo("#dropZone");
a++;
};
reader.readAsDataURL(files[i]);
} //end size validation
else{
oversize = true;
overzsizefiles += files[i].name+" is bigger than 1Mb \n";
}
} // end type validation
else{
found = true;
unAllowedFiles += files[i].name+" is not allowed \n";;
}
}
當我降大於1 MB的文件,它們不追加到所述DOM但是當我CONSOLE.LOG(filesArray)的長度對於所有的文件。例如
a.png > 1 MB
b.png > 512KB
c.png > 256KB
Alert will be thrown for a.png that it is oversize,
b.png and c.png will be appended to DOM,
console.log(fileArray) outputs [1: file, 2; file]
console.log(fileArray) output 3
由於filesArray[i]=files[i]
聲明中,如果塊if (files[i].size < allowedSize)
,我本來期望數組長度爲2
數組是基於零的,如果在索引2處有一個值,則無論數組中項目的數量如何,長度都將爲3([0,1,2])。 – adeneo
@ adeneo:感謝您的回覆。現在我懂了!!所以一個解決方法是隻有在有值時才從索引0推送! –
事實上,只要符合條件就使用push(),並且索引自我處理,長度將是正確的。 – adeneo