Question

I have read two similar posts on the subject and tried the provided solutions to use default values for parameters in a JavaScript function.

The solutions work when the terminal or ending parameters are missing yet if one of the intermediate parameter is missing the code does not seem to work.

Any possible hint on what I am doing wrong on this would help greatly as I am starting to convert my financial functions library for JavaScript

var tadJS = {
tadAEY: function(r, c)
{
    if (r==0.0)
        return 0.0;
    if (c==0.0)
        return Math.exp(r) - 1;
    else
    return Math.pow(1.0+r*c, 1/c) - 1;
},
tadPVIF2: function(r, n, c, p, d)
{
  var t=0.0;
  c = (typeof c !== "undefined") ? c : 1;
  p = (typeof p !== "undefined") ? p : 1;
  d = (typeof d !== "undefined") ? d : 1;
  t = (n-1)*p+d*p;
  if (r==0.0)
     return 1.0;
  return Math.pow(1.0+this.tadAEY(r,c),-t);
}
};

The following call to the function returns the value when the last three parameters are missing

document.write( "PVIF(10%, 10, 1, 1, 1) = " + tadJS.tadPVIF2(0.10,10) );

The following call to the JavaScript function does not work when the third parameter is missing

document.write( "PVIF(10%, 10, 1, 1/2, 1) = " + tadJS.tadPVIF2(0.10,10,,0.5) );

The following two threads were used as a reference for the solution to default parameters in JavaScript function

Is there a better way to do optional function parameters in Javascript?

Set a default parameter value for a JavaScript function

Était-ce utile?

La solution

It doesn't work because ,,0.5 is invalid JavaScript.

There are two simple solutions:

  1. Pass undefined for the parameters that you are omitting:

    tadJS.tadPVIF2(0.10, 10, undefined, 0.5);
    
  2. Optionally accept an object as the first argument:

    tadJS.tadPVIF2({r: 0.10, n: 10, p: 0.5});
    
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top