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?
Ian
51k13 gold badges104 silver badges111 bronze badges
asked Apr 25, 2013 at 15:26
Daniel Garcia Sanchez
2,3445 gold badges22 silver badges36 bronze badges
3 Answers 3
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...
}
answered Apr 25, 2013 at 15:29
Chris Dixon
9,1777 gold badges38 silver badges69 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
n = desired_start_point;
uno = this._uiElementsData[n].uiElementIndex;
dos = this._uiElementsData[n+1].uiElementIndex;
tres = ..
etc.
answered Apr 25, 2013 at 15:28
Laurence Moroney
1,2638 silver badges20 bronze badges
Comments
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
Paul S.
"I have to iterate in an array of objects" => the data structure is
[{}, {}, {}, ...], you shouldn't loop over this with for..in.Daniel Garcia Sanchez
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 ... :(
Paul S.
@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.
Paul S.
@alex23 I never
var inside a loop, I'd either var i; for (i = ... or I'd var i = ...; for (; ....Paul S.
@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. |
lang-js