Home > OS >  How to define a variable with another variable value
How to define a variable with another variable value

Time:03-30

I have a list of variables with dates as variable names like a290322, a300322, a310322 etc..

var a270322 = "https://google.com" ;
var a280322 = "https://youtube.com" ;
var a290322 = "https://facebook.com" ;
var a300322 = "https://twitter.com" ;
var a310322 = "https://instagram.com" ;
var a010422 = "https://sgquizdaily.com" ;
var a020422 = "https://maps.google.com" ;
var a030422 = "https://gmail.com" ;
var a040422 = "https://docs.google.com" ;

Now I want to declare a new variable named Today

The value of Today variable should match to the variable from the list of variables.

Manually day by day I can modify line like below.

var today = a300322 ;

But I don't know how to get it by script.

Can you help in assigning today dated variable value to Today?

CodePudding user response:

you can store the variable into an object so you can store and call the value based on the key like this

var a270322 = "https://google.com" ;
var a280322 = "https://youtube.com" ;
var a290322 = "https://facebook.com" ;
var a300322 = "https://twitter.com" ;
var a310322 = "https://instagram.com" ;
var a010422 = "https://sgquizdaily.com" ;
var a020422 = "https://maps.google.com" ;
var a030422 = "https://gmail.com" ;
var a040422 = "https://docs.google.com" ;

const variables = {
  a270322,
  a280322,
  a290322,
  a300322,
  a310322,
  a010422,
  a020422,
  a030422,
  a040422,
};

var today = 'a300322';

console.log(variables[today]); // https://twitter.com

CodePudding user response:

Get the current date through Date(), padding to 2 digits, slicing last two, prepend with 'a' and eval.

var a270322 = "https://google.com" ;
var a280322 = "https://youtube.com" ;
var a290322 = "https://facebook.com" ;
var a300322 = "https://twitter.com" ;
var a310322 = "https://instagram.com" ;
var a010422 = "https://sgquizdaily.com" ;
var a020422 = "https://maps.google.com" ;
var a030422 = "https://gmail.com" ;

const now = new Date()
var day = ('0'   now.getDate()).slice(-2)
var month = ('0'  (now.getMonth()   1).toString()).slice(-2)
var year = (now.getFullYear().toString()).slice(-2)
var Today = 'a'  day   month   year
console.log(Today)

TodaysUrl = eval(Today)
console.log(TodaysUrl)

  • Related