在JavaScript中可选参数 [英] Optional arguments in JavaScript
本文介绍了在JavaScript中可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么没有这个功能,如果余下的参数缺少抛出一个错误?
showStatistics(马克特谢拉,纽约扬基队,第一个基地);
下面是一个定义的函数:
函数showStatistics(姓名,团队,位置,平均,本垒打,RBI){
的document.write(< P><强>名称:LT; / STRONG>中+参数[0] +< BR />中);
的document.write(<强>团队:LT; / STRONG>中的论点+ [1] +< BR />中); 如果(typeof运算参数[2] ===字符串){
的document.write(<强>位置:其中; / STRONG>中+位置+< BR />中);
}
如果(typeof运算参数[3] ===数字){
的document.write(<强>安打率:< / STRONG>中+普通+< BR />中);
}
如果(typeof运算参数[4] ===数字){
文件撰写(<强>本垒打:LT; / STRONG>中+本垒打+< BR />中);
}
如果(typeof运算参数[5] ===数字){
的document.write(<强>击球后跑:< / STRONG>中+打点+< / P>中);
}
}
解决方案
这不通过任何参数显示为未定义
在函数内部。在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.
这篇关于在JavaScript中可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文