1

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" }
],
0

4 Answers 4

5

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];
Sign up to request clarification or add additional context in comments.

Comments

2
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" });

Comments

1

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" }');

Comments

1

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" });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.