...

View Full Version : Can I increment in a for in loop?



weismana81
03-02-2012, 07:28 AM
I'm super stuck. Is it possible to increment in a for...in loop? This is what I'm trying to do, but the increments aren't happening. Any help or advice is much appreciated!!



var i_1 = 3;
var i_2 = 8;

for (var key in data.id) {

if ([key] < '4')
{
attach_to = '.active';
}
else if ([key] > i_1 && [key] < i_2)
{
attach_to = '.item_' + i_1;

}

document.write(attach_to + '<br/>' + i_1+ '<br/>');
i_1 + 4;
i_2 + 4;
}

Old Pedant
03-02-2012, 07:47 AM
Increment what?

You mean here:


i_1 + 4;
i_2 + 4;

There is no incrementing being done by those statements. You add 4 to i_1 and then throw it on the floor. And do the same with i_2.

Perhaps you meant to do

i_1 += 4;
i_2 += 4;

THOSE statements will indeed increment each of those variables by 4.

But this code makes no sense either:


if ([key] < '4')

(1) The syntax is illegal. You are using square brackets in an inaprorpriate place.
(2) You are comparing something (not sure what, because the square brackets are illegal) to a *STRING* '4'. Are you aware that the string '1000000' is *LESS THANT the string '4'? If you want to compare NUMERIC values, use numbers, not strings.

Finally, I don't know when or where this code fragment is supposed to run, but if it runs at any point in time *AFTER* the HTML page is finished loading, it will WIPE OUT ALL CONTENTS in the page, including even the code you show here. You can't use document.write after a page is loaded.

weismana81
03-02-2012, 08:13 AM
Thanks so much for the guidance!

I didn't mean to be vague with the code. This is part of a much bigger project and I was just trying to break it down the specific problem I was having. I was just using document.write to help me visualize the output.

Silly mistake with the using strings instead of numbers :/ I've been using a lot of numbers with css to control behaviors on the page and I just... yeah...

Anyway, I really appreciate your help!! += was definitely what I was looking for and you no doubt saved me a silly amount of time catching that 'number' thing. Thanks!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum