There are similar questions like this, but they don't explain why this fails.
After dropping multiple files into the browser, iterating with the for...of statement fails while the normal for loop works.
The for...of version outputs undefined for file.name while the normal for version outputs the filename correctly.
Why?
function initDragDropEvents() {
// Trigger file uploads on drop events.
$('body').on('drop', function(e) {
let fileList = getFileListFromDropEvent(e.originalEvent);
// Have image? Update view.
for (const file in fileList) {
console.log('1 Dropped file: ' + file.name);
}
for (let i = 0; i < fileList.length; i++) {
console.log('2 Dropped file: ' + fileList[i].name);
}
});
}
function getFileListFromDropEvent(event) {
// Prevent default behavior, which opens the file.
event.preventDefault();
// Set default result for file.
let fileList = [];
// Get item list from @event.
let itemList = event.dataTransfer.items;
if (!itemList) {
itemList = event.dataTransfer.files;
}
if (itemList) {
for (const item of itemList) {
// Assume DataTransfer interface by default.
let file = item;
// Use DataTransferItemList interface instead?
if (item.kind === 'file') {
file = item.getAsFile();
}
fileList.push(file);
}
}
return fileList;
}
This was caused by a subtle bug. Rather than delete the question, will post the answer in case someone else makes the same mistake in the future.
This works if you use for...of and not for...in.