Daniel Garcia Sanchez
Daniel Garcia Sanchez

Reputation: 2344

loop for in an array of objects

I have to iterate through an object of objects with a for-loop.

I want to start the iteration at an index in the middle of the array - I don't want to start with the first element.

for(var i=elementId in this._uiElementsData)
    {
        cont++;

        if(cont == 1)
        {
            var element = this._uiElementsData[i];              
            uno = element.uiElementIndex;
        }
        else if(cont == 2)
        {
            var element = this._uiElementsData[i];              
            dos = element.uiElementIndex;
        }
        else if(cont > 2)   break;      

    }

I tried that, but it starts with the first element of the array... What am I doing wrong?

Upvotes: 0

Views: 82

Answers (3)

Paul S.
Paul S.

Reputation: 66304

You don't really want a for..in loop here, just a for loop

// start at index 1
for (var i = 1; i < this._uiElementsData.length; ++i) {
   // do stuff
}

Upvotes: 0

Chris Dixon
Chris Dixon

Reputation: 9167

Can't you just start at the half way index, like this?

var halfWay = (this._uiElementsData.length / 2);

// if 6 elements in the array / 2 = 3, start at 3rd element
for(var i= halfWay; i < this._uiElementsData.length, i++)
{
    var index = (i + 1); // index is zero based for the array, so plus 1
    var element = this._uiElementsData[i]; // 3rd item in the array... 
}

Upvotes: 2

Laurence Moroney
Laurence Moroney

Reputation: 1263

n = desired_start_point;
uno = this._uiElementsData[n].uiElementIndex;
dos = this._uiElementsData[n+1].uiElementIndex;
tres = ..

etc.

Upvotes: 1

Related Questions