Forum Moderators: open

Message Too Old, No Replies

Feature of JS

bug in Javascript?

         

kj6loh

11:26 pm on Nov 15, 2004 (gmt 0)

10+ Year Member


i=j++ and i=j+1 are suposed to yield the same results right?
Not so. Bear with me I have a code snippet here:

for ( var i = 0; i < stringToSearch.length; ++i ) {
result=stringToSearch.indexOf( key, i );
if ( result!=-1 ) {
++count;
//enable one and only one of the lines below.
i=result+1;
//i=result++;
}
else break;
}
alert (stringToSearch+" "+key+" "+count);

You will get interesting results

uncle_bob

11:39 pm on Nov 15, 2004 (gmt 0)

10+ Year Member



I thought that i=j++ increments the value of j, as well as assigning that value to i, whereas i=j+1 does not increment j, it just assigns a value to i.

Of course I could be wrong.

PCInk

12:05 am on Nov 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



uncle_bob you are correct:

i=j+1 means that i becomes the value of j plus one, j unaffected

i=j++ means that j is incremented and the i is set to the new j (which is old j+1)

i=++j (in c++, unsure about javascript) means that i becomes the value of (old) j, then j is incremented.

Eg) all examples start with j = 3

i=j+1; i should be 4, j should 3
i=j++; i should be 4, j should 4
i=++j; i should be 3, j should 4

bcc1234

12:27 am on Nov 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



i=j++ means that j is incremented and the i is set to the new j (which is old j+1)

i=++j (in c++, unsure about javascript) means that i becomes the value of (old) j, then j is incremented.

It's the other way around.

kj6loh

6:28 pm on Nov 16, 2004 (gmt 0)

10+ Year Member


But I'm talking about the lines below not the incrementers.

//enable one and only one of the lines below.
i=result+1;
//i=result++;

Since they are on a line by themselves shouldn't they do the same thing?

kj6loh

6:30 pm on Nov 16, 2004 (gmt 0)

10+ Year Member



Ok I see what you mean thanks.