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?

5
  • 2
    the method is forEach(function(v, i){}) Commented Apr 8, 2014 at 14:16
  • 2
    what is the purpose of sum and it as you are resetting it as soon after calculating it Commented Apr 8, 2014 at 14:17
  • Yes, forEach is the right one; You still can take a look at stackoverflow.com/questions/9329446/… Commented Apr 8, 2014 at 14:18
  • 1
    if it's jquery, it would be $.each(fields, function(i, v) {... Commented Apr 8, 2014 at 14:20
  • $.each(fields, func(){}); try with it. Commented Apr 8, 2014 at 14:21

3 Answers 3

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;
});
Sign up to request clarification or add additional context in comments.

Comments

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/).

Comments

0

If you are using jQuery:

$.each(fields, function(index, item){
    /* further processing */
});

1 Comment

As @A.Wolff points out, you shouldn't use $(selector).each() for this; instead $.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.

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.