简体   繁体   中英

Optional arguments in JavaScript

Why doesn't this function throw an error if the remaining arguments are missing?

showStatistics("Mark Teixeira", "New York Yankees", "1st Base");

Here is a the function defined:

function showStatistics(name, team, position, average, homeruns, rbi) {
  document.write("<p><strong>Name:</strong> " + arguments[0] + "<br />");
  document.write("<strong>Team:</strong> " + arguments[1] + "<br />");

  if (typeof arguments[2] === "string") {
    document.write("<strong>Position:</strong> " + position + "<br />"); 
  }
  if (typeof arguments[3] === "number") {
    document.write("<strong>Batting Average:</strong> " + average + "<br />");
  }
  if (typeof arguments[4] === "number") {
    document.write("<strong>Home Runs:</strong> " + homeruns + "<br />");
  }
  if (typeof arguments[5] === "number") {
    document.write("<strong>Runs Batted In:</strong> " + rbi + "</p>"); 
  }
}

Any argument that is not passed appears as undefined inside the function. In JavaScript there is no method overloading.

Remember that "arrays" in JS area actually associative. So the 2, 3, ... that you put in as indexed area really just hash keys. You could also check the value of arguments[54876]. That would not fail, but return to you undefined. So even though you're thinking of your parameter array as having only three valid indices and anything else giving you something along the lines of "index out of bounds", you really have three valid entries and lookup with any other keys don't fail, but give you undefined.

The parameters which aren't passed a value are set to undefined, which is not an error unless you try to do something with it that cannot be done with undefined. The only thing you are doing is checking if typeof undefined === 'number', which simply returns false, but does not throw an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM