sandeepKumar
sandeepKumar

Reputation: 811

How do I put a javascript variable inside javascript array?

I'm sure this is a simple question, but I couldn't find the answer.

I've included the code as well as my explanation.

var dates = "'2012-07-22','2012-07-26','2012-07-28'";

i have this JavaScript variable and i need to pass it the below filterDates array...something like this

filterDates = [dates]; 

or

filterDates = [document.write(dates)];

var filterDates = [];

I really don't know how to do it with JavaScript...for example we can do it in php like this

filterDates = [<?php echo $thatVariable; ?>];

How do I do this in JavaScript?

Upvotes: 0

Views: 125

Answers (2)

David Hedlund
David Hedlund

Reputation: 129792

Use split

filterDates = dates.split(',')

That will give you the following array:

filterDates = ["'2012-07-22'","'2012-07-26'","'2012-07-28'"]

If you want them to be actual dates, rather than string representations of dates, you'll have to do some more processing, but I'm not sure that's what you're after at all?

filterDates.forEach(function(d, i) { 
    filterDates[i] = new Date(d.replace(/\'/g, ''));
});

Upvotes: 5

Tejasva Dhyani
Tejasva Dhyani

Reputation: 1362

var filterDates = dates.split(',');
$.each(filterDates,function(i,val){
    filterDates[i] = val.split("'")[1];
})

Upvotes: 3

Related Questions