Tags
Asked 2026 years ago
30 Nov -0001
Views 300
Patricia

Patricia posted

Is FileList an array ?

Is FileList an array ?
jaggy

jaggy
answered Feb 27 '23 00:00

Yes, FileList is an array-like object in JavaScript , which contains a list of selected files from a file input element . Although FileList is not a true array, it behaves like one and has properties and methods that are similar to arrays.

For example, you can access individual files in a FileList object using bracket notation, just like you would with an array:

// Get the selected files from a file input element
const filesInput = document.querySelector('input[type="file"]');
const filesList = filesInput.files;

// Access the first file in the list
const firstFile = filesList[0];

You can also iterate over the FileList using a for loop or the forEach() method, just like you would with an array:


// Iterate over the files in the list using a for loop
for (let i = 0; i < filesList.length; i++) {
  const file = filesList[i];
  console.log(file.name);
}

// Iterate over the files in the list using forEach()
filesList.forEach(file => {
  console.log(file.name);
});

However, FileList does not have all the properties and methods of a true array, such as push(), pop(), slice(), and sort() . If you need to perform these operations on a FileList, you can convert it to a true array using Array.from():


// Convert a FileList to an array
const filesArray = Array.from(filesList);

// Use array methods on the converted array
filesArray.push(newFile);
filesArray.sort((a, b) => a.size - b.size);



Post Answer