0

I'm trying to figure out the best way to do something. I have a variable that acts as a HTML template, and insert properties from an array of objects. Simple code below:

i = 0;
v =  "<li>",
v += array[i].prop,
v += "</li>";

Array of objects:

array = new Array();
array[0] = { name: "1",
             prop: "Property 1"
           }
array[1] = { name: "2",
             prop: "Property 2"
           }

This is the bit thats getting me:

for (; i < array.length ;) {
    i += 1;
    console.log(i);
    $("body").append(v);
}

i returns as 0 and 1 in the console, but the prop value returns as "Property 1" twice. As far as I'm aware, since I haven't declared i in the for loop it should be returning the new value of i to the originally declared variable. This is obviously a scope issue that I'm missing/don't understand.

Thanks in advance.

13
  • What do you mean by "returning the new value of i to the originally declared variable"? Commented Jun 13, 2013 at 2:40
  • This is probably not a scope issue so much as a an order of execution issue. In what order is the actual code? (In the code you posted, you are using i in the assignment to v before you are assigning anything to i. Is that what actually happens?) Do you have any var declarations? Commented Jun 13, 2013 at 2:40
  • @cHao: i increases with each iteration, but isn't declared within the loop so its sits globally to the loop (I don't know the proper terminology...) Commented Jun 13, 2013 at 2:44
  • @TedHopp: The code is essentially that with a much longer "v" variable and a much longer set of object properties. I can get this to work if I declare i like this: for (i = 0; ....; i++) and I move the variable v into the loop scope, but this isn't ideal for this situation. Commented Jun 13, 2013 at 2:46
  • 2
    @JamieStrauss - v is not reassigned inside the loop, how is it expected to change? Commented Jun 13, 2013 at 2:54

2 Answers 2

2

v is not reassigned inside the loop. You append the same value multiple times.

Sign up to request clarification or add additional context in comments.

Comments

1

Not exactly sure what your problem is, but in terms of "best way to do something" I would go:

var array = [
        {
            name: "1",
            prop: "Property 1"
        },
        {
            name: "2",
            prop: "Property 2"
        }   
    ],
    i = 0,
    v;
for (; i < array.length; i++) {
    v = '<li>' + array[i].prop + '</li>';
    $("body").append(v);
}

1 Comment

This is how its done, I only changed it to explicitly stated indexes to make the question clearer...

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.