JavaScript 中的可选参数 [英] Optional arguments in JavaScript
本文介绍了JavaScript 中的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果缺少剩余参数,为什么这个函数不会抛出错误?
Why doesn't this function throw an error if the remaining arguments are missing?
showStatistics("Mark Teixeira", "New York Yankees", "1st Base");
这是定义的函数:
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>");
}
}
推荐答案
任何未传递的参数在函数内都显示为 undefined
.在 JavaScript 中没有方法重载.
Any argument that is not passed appears as undefined
inside the function. In JavaScript there is no method overloading.
这篇关于JavaScript 中的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文