0

I'm using javascript and JQuery.

let's assume there's an array, ListArray and it's got a bunch of sentences inside. Simple.

Can I somehow do this?

var List = for (var i = 0; i < 10; i++) {
    //loop through an array here to generate the contents
}

I need to generate a lot of list groups, and within each of those list groups, generate a list, and the lists' contents are stored in an array.

So how can I generate this list from the array and store it in that variable?

the variable should have an outcome of

var List = "<p>Some content from an array</p><p>Some content from an array</p><p>Some content from an array</p>";

To be clear, I'm asking if it's valid to put an for loop within a variable in JS.

0

3 Answers 3

1

Just add to the variable inside the loop:

var list = '';

for (var i = 0; i < 10; i++) {
   list += '<p>' + generateContentForGroup(i) + '</p>';
}

where generateContentForGroup would somehow get the ith array and generate from it the content you want.


I'm asking if it's valid to put an for loop within a variable in JS.

No it's not. This would result in a syntax error. On the right hand side of a variable declaration with assignment can only be an expression:

var variable_name = expression;

A for loop is a statement and hence cannot be used in place of an expression.

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

Comments

1

How about using a bit of jQuery.map

var arr = [
             "Some content from an array",
             "More content from an array",
             "Even more content from an array"
          ];
var str = $.map(arr,function(e){ return "<p>" + e + "</p>"}).join('');
//output: <p>Some content from an array</p><p>More content from an array</p><p>Even more content from an array</p>

Live example: http://jsfiddle.net/s874S/

Comments

0

Try:

ary = ["some text1","some text2","some text3"];
var list = "";
var len = ary.lengthl
for (var i = 0; i < len; i++) {
    list += "<p>"+ary[i]+"</p>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.