0

From what I understand, the error means there's an illegal character somewhere. When I open my debugger it is telling me the "<" in for (var i=0, i<6, i++) is not allowed.

This is the context if needed:

var largeArray = new Array(6);
for (var i=0, i<6, i++)
    {
        if (largeArray[i] == undefined)
        {
            largeArray[i] = "<img src='image/"+temp+".jpg'/>";
            document.getElementById("la").innerHTML = largeArray[i];
        }
    }

2 Answers 2

8

for (var i=0, i<6, i++) should be: for (var i=0; i<6; i++)

The comma is for multiple intializations, like: for (var i=0, j=0, k=0; i<6; i++)

Also, JSLint will hurt your feelings, but save you headaches ;)

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

5 Comments

In addition to using commas for multiple variable declarations with var you can use it to stick multiple expressions where a single one might normally be expected. Here's a practical example of this with a for loop: for (var i=0,j=0,k=100; i<6; i++,j+=4,k--)
Yes, but I would recommend you NEVER do this because it will cause a bug (probably more than one). Use a for loop only if you absolutely have to, use a for each or map for generic cases.
Why on earth would it cause a bug? If (for whatever reason) one needs to increment/change several variables at the end of each loop iteration this will work perfectly. Your own example set three variables at the start of the loop, so why would you rule out needing to update three variables each time through? I don't need to do it often, but it happens from time to time.
You can put any additional increments inside the execution loop. It wont cause a bug right away, but one year later when you change something it will, because you didn't expect the additional increment there. Just because a language can do something, doesn't mean it's a good idea.
Let's agree to disagree. I agree with your last sentence about not all language features being a good idea, but I disagree that this is one of those cases. My coding isn't perfect, but I can guarantee I would never introduce a bug due to this feature because I would never modify a for loop without first reading all three parts of the for ([initialization]; [condition]; [final-expression]) statement. The last part of the for statement is intended to hold "An expression to be evaluated at the end of each loop iteration" (to quote MDN), and that's what I use it for.
4

You need to replace your comma's with semi-colons:

Change this:

for (var i=0, i<6, i++) 

To this:

for (var i=0; i<6; i++) 

Comments

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.