1

Hi,

I have this JavaScript code

function mycode(con) {
 var date1="feb-9";
 var date2="feb-11";
 var date3="feb-20";
 var getdate = con;
    document.write(getdate);

}

This code is supposed to display a specific date depending on the given argument like below:

<script type="text/JavaScript">mycode("date1");</script>

It wont work because all I get is "date1" instead of the value for that variable which should be "feb-9".

What I am doing wrong?

Cain Nuke
  • 2,843
  • 5
  • 42
  • 65

2 Answers2

7

You can't create a dynamic variable that way. Use an object. Then you can use [] notation for variable property names

function mycode(con) {
    var dates = {
        date1: "feb-9",
        date2: "feb-11",
        date3: "feb-20"
    };
    alert(dates[con]);    
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

You are simply printing the string

Try this

function mycode(con) {
var date ={
 'date1': "feb-9",
 'date2': "feb-11"
}
var getdate = "not found";
    for( var k in date){
    if(k == con){
        getdate = date[k]
    }
  }     
  alert(getdate);  
}
mycode("date1");

https://jsfiddle.net/

Siddhartha Chowdhury
  • 2,724
  • 1
  • 28
  • 46