Alex Rivera | Logout

$.each() index start number in jQuery

Asked 2011-02-03T22:07:13.913
11

How do I start jQuery $.each() index from 1 instead of 0?

I am using .each function to populate select box. So here I want to populate options in the select box from 1. So based on a condition I want to add option in first index i.e 0.

Edit
Report

2 Answers

9

$.each

So try

$.each(obj, function(i, elem) {
    if (i === 0) return;
    // do stuff
});

Alternatively rewrite your code so its so indexes and data start at 0. JavaScript is interally 0 based rather then 1 based like Matlab and some other languages.

answered 2011-02-03T22:09:42.613
3

Not possible. jQuery.each loops over Objects (Arrays). For real objects, it uses a for in loop. Objectpropertys don't have a guaranteed index at all by the way.

For Arrays it uses standard for loop, but you don't have access to the starting index.

Your best shot is to just skip the first element.

$.each(obj, function(index, elem) {
    if( index === 0 )
        return true;

    // code
});
answered 2011-02-03T22:11:42.847

Your Answer