Elfy
Elfy

Reputation: 1863

Call function on each array element

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.

Upvotes: 0

Views: 1306

Answers (2)

jfriend00
jfriend00

Reputation: 707416

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.

Upvotes: 3

Erick
Erick

Reputation: 1022

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

Upvotes: -1

Related Questions