user947462
user947462

Reputation: 949

concatenate var in loop

A basic question please, I am trying this code:

var number_questions = postsJSON1[i]['question'].length;
for (a=0; a<number_questions; a++) {
var post+[a] = postsJSON1[i]['question'][a];    
}

this line give an error: var post+[a]

What is the correct way ?

Upvotes: 2

Views: 14133

Answers (2)

Wayne
Wayne

Reputation: 60424

It's hard to see exactly what you're trying to do, but I think you want this:

var number_questions = postsJSON1[i]['question'].length;
var post = "";
for (a = 0; a < number_questions; a++) {
    post += postsJSON1[i]['question'][a];    
}

I'm assuming that postsJSON1[i]['question'] is an array, since you're treating it as such in the body of the loop. That's why I've changed the first line to use the length property to init number_questions.

By the way, this code is functionally equivalent to join; you could do the same thing in one line:

var post = postsJSON1[i]['question'].join("");

Upvotes: 1

PeeHaa
PeeHaa

Reputation: 72729

This will get you an array:

var number_questions = postsJSON1[i]['question'];
var post = [];
for (a=0; a<number_questions; a++) {
  post[a] = postsJSON1[i]['question'][a];    
}

This will get you a string:

var number_questions = postsJSON1[i]['question'];
var post = '';
for (a=0; a<number_questions; a++) {
  post += postsJSON1[i]['question'][a];    
}

BTW I don't know the contents of postsJSON1[i]['question'], but the following looks a bit weird:

var number_questions = postsJSON1[i]['question'];

Shouldn't that be:

var number_questions = postsJSON1[i]['question'].length;

?

Upvotes: 9

Related Questions