2013-11-27 72 views
0

下面的代碼基本上遍歷掉落的文件,將文件對象壓入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

+0

數組是基於零的,如果在索引2處有一個值,則無論數組中項目的數量如何,長度都將爲3([0,1,2])。 – adeneo

+0

@ adeneo:感謝您的回覆。現在我懂了!!所以一個解決方法是隻有在有值時才從索引0推送! –

+0

事實上,只要符合條件就使用push(),並且索引自我處理,長度將是正確的。 – adeneo

回答

1

你做filesArray[i]=files[i];因此,如果最後一個項目通過了大小測試,然後filesArray會設置爲全長,即使中間的某些項目未分配。 Javascript .length報告比分配的最高數組元素高一個。

在這個簡單的測試,你可以看到正在發生的事情:

var x = []; 
x[10] = "foo"; 
alert(x.length); // alerts 11 

要解決它,你可能想改變:

filesArray[i]=files[i]; 

這樣:

filesArray.push(files[i]); 

然後,filesArray wi只有通過尺寸測試的物品纔有它的長度,它的長度將與其中的物品數量相匹配。

+0

你是一個真正的!奇蹟般有效!! –