1

I'm pushing to an array in jQuery and I can't do .each on that array afterwards, what is causing it?

Fiddle

var sections = [];
for (var j = 0; j < 15; j++) {
  sections.push("tests-" + j);
}

console.log(sections);  // this is a proper array

sections.each(function(){
  console.log("test");  // Uncaught TypeError: undefined is not a function
});
Weafs.py
  • 22,731
  • 9
  • 56
  • 78
Wordpressor
  • 7,173
  • 23
  • 69
  • 108

1 Answers1

2

There is no Array.prototype.each method, either use Array.prototype.forEach or jQuery $.each utility function. The each method that you are trying to use, belongs to jQuery objects and is used for iterating through the collections. You could use the $(sections).each(fn) syntax for creating jQuery object from an array and using it's each method, but that's a bad idea and should be avoided as the sections is not an array of DOM elements.

Note that jQuery has 2 each methods, one is a utility function and another is a method of jQuery object.

You can use this.each when you are defining a jQuery method as this in that context refers to a jQuery object which is an array-like object i.e. it has some of the Array methods but it's not a real array, it's a jQuery object, you can call the .get() method on the jQuery objects for getting the internal arrays, now the returned array has .forEach() method but not .each() method.

sections.forEach( function(elem) { console.log(elem); });
$.each(sections, function(index, elem) { console.log(elem); }); 
Ram
  • 143,282
  • 16
  • 168
  • 197
  • This is really confusing as I'm using this.each a few lines above and it seems to be working there: http://stackoverflow.com/questions/26962363/jquery-plugin-development-return-this-each-issue - could you please explain why does it work there and wouldn't in this scenario? Because the first one is a DOM element and here's just an JS-array? – Wordpressor Nov 16 '14 at 23:04