0

I'm trying to do a for loop in a string. This is what I have:

slideContainer.append('<div>' + for( i=0; i<=slideCount-1; i++ ){'<a>' + (i+1) + '</a>'} + '</div>');

What I want is for it to end up like this:

<div>
  <a>1</a>
  <a>2</a>
  <a>3</a>
  <a>4</a>
  <a>5</a>
</div>

but I'm getting an error:

Uncaught SyntaxError: Unexpected token ( 

It's referring to the one next to 'for'. What's going on?

1
  • 2
    Your code is illegal. That's what's going on. You can't do it like that. Commented Feb 3, 2014 at 19:49

4 Answers 4

3

In short -- for is instruction (statement), not an expression which returns value.

Usually we write instruction as for () while expression (like function) are written as fan() -- space before ( means that this is not expression.

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

Comments

2

Your code is illegal. Instead use a for loop to concatenate string and the add it to div

var str = "";
for (i = 0; i <= slideCount - 1; i++) {
    str += '<a>' + (i + 1) + '</a>';
}
slideContainer.append('<div>' + str + '</div>');

Comments

2
function returnSlideNum(slideCount)
{
var _ret = "";
for( i=0; i<=slideCount-1; i++ ){_ret+='<a>' + (i+1) + '</a>';}
return _ret;
}

slideContainer.append('<div>' + returnSlideNum(slideCount) + '</div>');

Comments

0

You can't do it like that. You could try something like this:

slideContainer.append('<div>' + 
(function() { 
    var str = "";
    for(var i=0; i<=slideCount-1; i++ ){ 
        str += '<a>' + (i+1) + '</a>'
    } 
    return str;
})()
+ '</div>');

fiddle

This wraps your for loop in an immediately invoked function expression (IIFE) which, as the name suggests, is an expression and therefore valid. But that's pretty ugly. Better would be to have append inside your loop:

var aDiv = $("div");
for (var i=0; i < slideCount; i++) {
    aDiv.append('<a>' + (i+1) + '</a>');
}
slideCountainer.append(aDiv);

fiddle

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.