up vote 1 down vote favorite
share [g+] share [fb]

I need to dynamically create an array based on a range. I have a req_count variable. My array needs to always have the first 6 spots as null, and then the variable spots as { "sType": "title-string" }. For some reason, my code below doesn't seem to be working. Any ideas?

Javascript:

var aoColumns = ['null', 'null', 'null', 'null', 'null', 'null']

for (i=0;i<=req_count;i++){

    aoColumns.push('{ "sType": "title-string" }');

}

So if req_count = 5, the result should be:

[   
    null,   
    null,
    null,
    null,
    null, 
    null,                                   
    { "sType": "title-string" },
    { "sType": "title-string" },
    { "sType": "title-string" },
    { "sType": "title-string" },
    { "sType": "title-string" }
],
link|improve this question

What is it doing ? – Hans B PUFAL Jan 15 at 20:54
feedback

4 Answers

up vote 5 down vote accepted

You're pushing strings, not objects:

Change

for (i=0;i<=req_count;i++){
    aoColumns.push('{ "sType": "title-string" }');
}

to

for (i=0;i<=req_count;i++){
    aoColumns.push({ "sType": "title-string" });  
}

The same goes for your initial null values. You're pushing the string "null" instead of actual null.

Change

var aoColumns = ['null', 'null', 'null', 'null', 'null', 'null']

to

var aoColumns = [null, null, null, null, null, null];
link|improve this answer
feedback
var aoColumns = ['null', 'null', 'null', 'null', 'null', 'null']

should be

var aoColumns = [null, null, null, null, null, null]

and

aoColumns.push('{ "sType": "title-string" }');

should be

aoColumns.push({ "sType": "title-string" });
link|improve this answer
feedback

Remove the quotes from inside the push... Push real objects into it, not strings.

For example:

aoColumns.push({ "sType": "title-string" });

Instead of

aoColumns.push('{ "sType": "title-string" }');
link|improve this answer
feedback

String is not the only type in javascript ;). 'null' should be null and

aoColumns.push('{ "sType": "title-string" }');

should be

aoColumns.push({ "sType": "title-string" });

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.