Javascript-仅返回未定义的数组索引
这是我的代码:Javascript-仅返回未定义的数组索引,javascript,arrays,indexing,undefined,Javascript,Arrays,Indexing,Undefined,这是我的代码: var fr = new FileReader(); var readFiles; var fileI; var files; fr.onload = () => { readFiles.push(fr.result); fileI ++; if (fileI < files.length) { fr.readAsDataURL(files[fileI]); } }; function getVideoImage(path, secs, c
var fr = new FileReader();
var readFiles;
var fileI;
var files;
fr.onload = () => {
readFiles.push(fr.result);
fileI ++;
if (fileI < files.length) {
fr.readAsDataURL(files[fileI]);
}
};
function getVideoImage(path, secs, callback) {
var me = this, video = document.createElement('video');
video.onloadedmetadata = function() {
if ('function' === typeof secs) {
secs = secs(this.duration);
}
this.currentTime = Math.min(Math.max(0, (secs < 0 ? this.duration : 0) + secs), this.duration);
};
video.onseeked = function(e) {
var canvas = document.createElement('canvas');
canvas.height = video.videoHeight;
canvas.width = video.videoWidth;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
var img = new Image();
img.src = canvas.toDataURL();
callback.call(me, img, this.currentTime, e);
};
video.onerror = function(e) {
callback.call(me, undefined, undefined, e);
};
video.src = path;
}
$uploadFiles.on("input", () => {
files = $uploadFiles[0].files;
var value = $uploadFiles[0].value;
fileI = 0;
readFiles = [];
fr.readAsDataURL(files[0]);
for (var i = 0; i < files.length; i++) {
var format = files[i].name.split(".").pop().toUpperCase();
var thumbnail;
getVideoImage(readFiles[i], 0, (img) => {
thumbnail = img;
});
if (fileFormat.video.includes(format)) {
propertiesData.FILES.contents[0].push({
thumbnail: thumbnail,
title: files[i].name,
file: readFiles[i]
});
} else if (fileFormat.image.includes(format)) {
console.log(readFiles);
console.log(i);
console.log(readFiles[i])
propertiesData.FILES.contents[1].push({
thumbnail: readFiles[i],
title: files[i].name,
file: readFiles[i]
});
} else if (fileFormat.audio.includes(format)) {
propertiesData.FILES.contents[2].push({
thumbnail: "Assets/Logo.PNG",
title: files[i].name,
file: readFiles[i]
});
} else {
alert("File Format Not Supported");
}
$("#properties-left-menu li[style='color: ${color[1]}']")
}
});
console.log(readFiles);显示原始文件数组,如和
控制台日志(i);显示正确的索引
所以
log(readFiles[i]);应该显示一个原始文件字符串,但它只显示未定义的字符串。为什么?出于性能原因,浏览器控制台在以后只评估引用(如对象引用或数组)。因此,它不会显示执行log语句时的实际内容 发件人: 请注意,如果您在最新版本的Chrome和Firefox中记录对象,那么您在控制台上记录的是对该对象的引用,它不一定是您调用console.log()时该对象的“值”,而是您单击该对象打开时该对象的值 要获取当时的实际内容,请使用
console.log(readFiles.toString());
然后您将看到,此时数组仍然为空,因为FileReader.readAsDataURL()是异步执行的
进一步阅读:
FileReader
onload
事件是异步的,for
循环是同步的,除非使用了async/await
。@guest271314console.log(i)
输出正确的索引(0,1,2,3…)如果(fileI
在文件阅读器
onload
处理程序中?是否设置了多个属性?为什么执行fr.readAsDataURL(文件[0])
时,下一行是迭代文件的循环的对象?
console.log(readFiles.toString());