数组长度不等于数组对象

Array length is not equal to array objects

本文关键字:数组 对象 不等于      更新时间:2023-12-09

下面的代码基本上遍历已删除的文件,将文件对象推入filesArray,并在文件满足标准(小于1mb且为png/jpg/fig)的情况下将文件附加到DOM。我已将允许的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";;
    } 
  }

当我丢弃大于1MB的文件时,它们不会附加到DOM中,但当我控制台.log(filesArray)时,长度是所有文件的长度。E.g

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块if (files[i].size < allowedSize)中声明的,因此我希望数组长度为2

您正在执行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中只有通过尺寸测试的项目,其长度将与其中的项目数量相匹配。