0

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?

3 Answers 3

2

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

Comments

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

etc.

Comments

0

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
}

6 Comments

"I have to iterate in an array of objects" => the data structure is [{}, {}, {}, ...], you shouldn't loop over this with for..in.
Sorry, but I didn't explained well...I really have a object of objects...if like an array, but not really an array...so I can't use length ... :(
@Daniel - An Object which is not/does not inherit from Array does not have a defined "order" for it's keys, so the question doesn't make sense.
@alex23 I never var inside a loop, I'd either var i; for (i = ... or I'd var i = ...; for (; ....
@alex23 It extends from how I only use one var for a whole Function; it means you can look in one place for all variables that have been given scope meaning you only var each variable name once, and (by putting it at the top) don't have to worry as much about how var is hoisted, which may cause unexpected undefined or scope capturing. Having a var inside a loop would mean I'd var for each loop, or that my loops couldn't be re-ordered without changing them. It really just comes down to a style of writing code.
|

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.