0

I'm trying to pass every element of an array to my function:

e.target.files.forEach(myfunction);

But I get this error:

Uncaught TypeError: Object # has no method 'forEach'

I did a console log on it and confirmed the array is not empty.

2
  • Whatever e.target.files is, it doesn't have a forEach() method. Commented Nov 23, 2013 at 2:16
  • Try [].forEach.call(e.target.files, function(){}) Commented Nov 23, 2013 at 2:21

2 Answers 2

3

e.target.files is probably not a real Array so it doesn't have a forEach() method. I'm guessing it is a FileList object.

You may have to iterate it yourself or apply array methods to it indirectly.

var files = e.target.files;
for (var i = 0; i < files.length; i++) {
    myfunction(files[i]);
}

FYI, it is common for the DOM to use pseudo Array types of data structures that have a .length property and can be indexed with [index], but are not actual Array objects so they don't have all the other array methods. NodeList is another such Array-like object used by the DOM that isn't an actual array.

It is also possible to copy this psuedo-array into an actual array or apply some array methods to it using .call() or .apply(), but I don't see that as necessary here. I'd for for the simple for loop above as it's nice and clear what is happening.

Sign up to request clarification or add additional context in comments.

Comments

-1

Foreach is not a default method to array. If you copied this code, verify which file is beeing added.

2 Comments

forEach is a standard method on Array since ECMAScript 5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.