Is there a way to set a condition, making one parameter different depending on another parameter? Javascript

StackOverflow https://stackoverflow.com/questions/23611600

  •  20-07-2023
  •  | 
  •  

Question

I have a parameter in my report that takes place for This_year, and I need to fill the void on the Last_yr parameter depending on what This_year is.

if(params["This_year"] == "1/1/14"){
this.params = this.params.replace("Last_year", "2013")}

Is this how to do it, or is it even possible?

Était-ce utile?

La solution

It's not clear what "this" is in this context! But assuming the following object:

params = {
   This_year: "1/1/14",
   keyA : "valueA",
   keyB : "valueB"
};

If you assign a value to params, you're basically overwriting it, for example:

params = null;

params.hasOwnProperty("This_year") will return false!

I wonder why you say "make X different", so I'll assume you mean, change existent key value:

params = {
   This_year: "1/1/14",
   Last_year: "xxxx"
};

params.Last_year = "YYYY";

So, you can set a property with a value on the parameters object, as in:

var params = { This_year: "1/1/14" }; 

if (params.hasOwnProperty("This_year") && params.This_year === "1/1/14") { 

   params["Last_year"] = "2013"; 

}

I would recommend to normalize the date, so you don't have to hard type:

if (params.hasOwnProperty("This_year") && params.This_year === "1/1/2014") { 

  params.Last_year = ( new Date("1/1/14").getFullYear() - 1);

}

Since "1/1/14" would return year 1914 and "1/1/2014" return 2014.

Hope this helps!

Autres conseils

I'm not sure what you mean; something like this:

Here we have a function year that accepts two arguments (=parameters). The first one is required, the second one is optional:

function year(thisYear, lastYear) {
    lastYear = lastYear || thisYear.getFullYear()-1;

    alert(thisYear, lastYear);
}

When we call the function and pass a date (-object) to argument thisYear : year(new Date()) without the second argument, the second argument automatically becomes thisYear's year -1.

Of course, what we are doing here depends on the object we use (Date). If you don't want to do this, we can make a custom function with your date format (dd/mm/yyyy):

function getLastYear(dateString) {
    var dates = dateString.split('/');

    if (dates.length>=3) {
        //    we assume:
        //    dates[0] = day
        //    dates[1] = month
        //    dates[2] = year.
        return dates[0] + '/' + dates[1] + '/' + (dates[2]-1);
    }
}

Now we can use this for the following:

var lastYear = getLastYear(thisYear);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top