tags:

views:

93

answers:

2

Javascript's foreach equivalent:

for ( var i in products )
{
    document.write("Write" + i + 1 );
}

Output:

Write01

Edit: I tried parsing i into an integer.

for ( var i in products )
{
    document.write("Write" + parseInt(i) + 1 );
}
+10  A: 

Because i is a number, but gets cast to a string by the first +. Use this:

for ( var i in products ) {
  document.write(""); document.write("Write" + (i + 1) );
  // ------------------------------------------^
}
Boldewyn
Thanks! STH had the same answer but you had an explanation.
Doug
You're welcome.
Boldewyn
+1 <offtopic>I think he is, but I guess it could be taken either way. </offtopic>
Dead account
A: 

The issue here is operator precedence. As shown in that table, the + operator associates left-to-right.

So:

a + b + c

Is grouped as follows:

((a + b) + c)

So in your original code, the expression is grouped as follow:

("Write" + i) + 1

In other words, it's a string concatenation followed by another string concatenation. Since you intend to do the arithmetic addition (i + 1) first, you'd have to group them explicitly:

"Write" + (i + 1)
polygenelubricants