Adam
Adam

Reputation: 6122

javascript .forEach loop with nested code

I have this code:

function uploadFiles(event) {
    event.preventDefault();

    files = [...fileElem.files]

    files.forEach(uploadFile)

}

function uploadFile(file, i) {

}

Now, I want to add code to files.forEach(uploadFile)

Pseudo code: files.forEach(
uploadFile(); console.log(file.name); )

I looked here: For-each over an array in JavaScript So I tried:

files.forEach(function(uploadFile) {
    uploadFile();
    console.log(file.name); 
})

files.forEach(function (entry) {            
    console.log(entry.name);
    uploadFile(entry);
})

But I guess I don't understand how this works. How can I execute the function uploadFile and access the properties of file in the same codeblock?

Upvotes: 0

Views: 117

Answers (3)

IVO GELOV
IVO GELOV

Reputation: 14259

Use this code:

function uploadFiles(event) 
{
    event.preventDefault();

    files = [...fileElem.files]

    files.forEach(extendedUploadFile)
    clearFileInput(fileElem);
}

function uploadFile(file, i) 
{
 ....
}

function extendedUploadFile(file, i)
{
    console.log(file.name);
    uploadFile(file, i);
}

// reset/clear FILE type inputs
function clearFileInput(ctrl)
{
  try
  {
    ctrl.value = null;
  }
  catch(ex)
  { }
  if (ctrl.value) ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
}

Upvotes: 1

M.Soyturk
M.Soyturk

Reputation: 370

As Andreas pointed out, Mozilla's forEach documentation is sufficient enough to understand how it works.

function logArrayElements(element, index, array) {
   console.log('a[' + index + '] = ' + element)
}

[2, 5, 9].forEach(logArrayElements)

When you iterate over an array, for each element you get the element, index and the array object being traversed. In your case you don't need the array object being traversed for each element. So you can ignore it and do something like this:

function uploadFiles(event) {
    event.preventDefault();
    files = [...fileElem.files]
    files.forEach(uploadFile)
}

function uploadFile(file, index) {
    console.log(file.name) (Reach the properties of the file)
    ... (Do the uploading)
}

Upvotes: 0

Desu
Desu

Reputation: 900

I think you want to do something like this:

files.forEach( file => {
       uploadFile(file);
 });

Not sure what i meant on upload file, guessing it's an iterator:

for(var x = 0; x < files.length){
uploadFile(file[x],x);
}

Upvotes: 0

Related Questions