数组长度不等于数组对象
Array length is not equal to array objects
下面的代码基本上遍历已删除的文件,将文件对象推入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
中只有通过尺寸测试的项目,其长度将与其中的项目数量相匹配。
相关文章:
- 将数组对象传递到struts2中的操作类
- 如何使用jquery返回php-json数组对象
- 从其名称获取javascript数组对象
- 值未与数组对象绑定
- 如何按数组/对象值的倍数过滤对象数组
- 在表中显示数组对象
- 在数组对象中分组
- 将第二个或多个数组推送到数组对象 AngularJS 中
- 重新排列 JavaScript 数组/对象
- 键上的javascript数组对象过滤器
- handontable:在不更改数据数组/对象的情况下隐藏某些列
- 用于跟踪购物车可用性的Javascript数组/对象/哈希表
- 重建有角度的java脚本数组对象
- 对JSON数组对象进行排序
- 连接与数组对象相关的文本:方式和位置
- 哪些浏览器和版本支持将常见的类数组对象直接传递到fn.apply()
- 如何使用Handlebars循环数组对象和模板
- 是否可以引用JS数组/对象中的另一个元素
- Javascript中的名称索引-数组/对象
- 数组长度不等于数组对象