0

I have this code

var fields = [
    'ile_sprzedal', 'ile_zarobil', 'srednia_kwota', 'konwersja', 'punkty'
];
fields.each(function(i, v){
    var sum = sum_ + v;
        sum = 0;
    var it = it_ + v;
        it = 0;
});

and this error: TypeError: Object [object Array] has no method 'each'. And the question is - How to call each method on some array?

Lukas
  • 7,384
  • 20
  • 72
  • 127

3 Answers3

3

Array does not have a each() method, it has forEach() like - Supported by IE>=9

var fields = [
    'ile_sprzedal', 'ile_zarobil', 'srednia_kwota', 'konwersja', 'punkty'];
fields.forEach(function (v, i) {
    var sum = sum_ + v;
    sum = 0;
    var it = it_ + v;
    it = 0;
});

Or jQuery has a $.each() method - cross browser

var fields = [
    'ile_sprzedal', 'ile_zarobil', 'srednia_kwota', 'konwersja', 'punkty'];
$.each(fields, function (i, v) {
    var sum = sum_ + v;
    sum = 0;
    var it = it_ + v;
    it = 0;
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

If you are using jQuery:

$.each(fields, function(index, item){
    /* further processing */
});
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
  • As @A.Wolff points out, you shouldn't use [`$(selector).each()`](http://api.jquery.com/each/) for this; instead [`$.each()`](http://api.jquery.com/jQuery.each/) should be used if you are iterating over an array or object. They have similar names and can easily be confused, but they are not the same. – Useless Code Apr 08 '14 at 14:40
0

Well fields is just a plain array. The $().each() (https://api.jquery.com/each/) call is restricted for jQuery objects. So you need to either wrap fields in a jQuery object ($(fields).each) or just use the $.each call: $.each(fields, function(i, v) (https://api.jquery.com/jQuery.each/).

Igor
  • 33,276
  • 14
  • 79
  • 112