帮助我编写一个简单的函数,在未声明时传递参数值 0
我不知道最好的编写方式是什么以及如何...我有一个像
function myFunc(myVal1, myVal2){/*... various things ...*/};
myVal1 和 myVal2 是数字的
函数有时我希望能够通过调用 myFunc(myVal1 )。这样做我希望 myVal2 的标准值(如果没有声明的话)为 0。
我想写一些东西,
function myFunc(myVal1, myVal2){
if(myVal2 == NaN)
myVal2 = 0;
}
}
但我不认为这是正确的方法。 非常感谢您的帮助!
I don't know what is the best way to write it and how to... I have a function like
function myFunc(myVal1, myVal2){/*... various things ...*/};
where myVal1 and myVal2 are numbers
Sometimes I want to be able to recall the function passing only one parameter just by calling myFunc(myVal1). Doing so I want that myVal2 would have a standard value, if not declared, of 0.
I was thinking to write something
function myFunc(myVal1, myVal2){
if(myVal2 == NaN)
myVal2 = 0;
}
}
But I don't believe that it is the right way to do it.
Thx very much for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
未设置的参数的类型未定义,请像这样测试它。
Arguments that are not set have type undefined, test for it like this.
应该可以解决问题。
更多通往罗马的方法(除了
typeof myVal2 == "undefined"
):最后,特别是对于 David马滕森
should do the trick.
more ways to Rome (besides
typeof myVal2 == "undefined"
):and finally, especially for David Mårtensson
如果您希望 myVal2 默认为 0 以外的任何值,则必须更加明确,因为 0 的计算结果为 false。所以:
If you want myVal2 to default to anything other than 0, you have to be more explicit, as 0 evaluates to false. So: