admin管理员组文章数量:1401407
Currently, I have a function defined like:
function a(b,c) {
if (typeof(b) === "undefined") { b = 1; }
if (typeof(c) === "undefined") { c = 2; }
...
}
Before, it set to default if the value was falsy. Changing this breaks the following call:
a(null, 3);
There is no undefined object. How can I pass only the second argument?
There is, actually, an undefined object:
There may be an undefined object normally, but clearly in my environment something has gone awry
Currently, I have a function defined like:
function a(b,c) {
if (typeof(b) === "undefined") { b = 1; }
if (typeof(c) === "undefined") { c = 2; }
...
}
Before, it set to default if the value was falsy. Changing this breaks the following call:
a(null, 3);
There is no undefined object. How can I pass only the second argument?
There is, actually, an undefined object:
There may be an undefined object normally, but clearly in my environment something has gone awry
Share Improve this question edited Jan 12, 2013 at 4:26 cacba asked Jan 12, 2013 at 4:15 cacbacacba 4134 silver badges9 bronze badges3 Answers
Reset to default 4There is, actually, an undefined
object:
a(undefined, 3);
It, is, however, for some reason, a variable, so someone could do :
undefined = 2;
Your code wouldn't work any more. If you want to protect yourself against someone redefining undefined
, you can do this:
a(void 0 /* zero's not special; any value will do */, 3);
The void
prefix operator takes a value, discards it, and returns undefined
.
A good test for checking the existence of a variable is this:
(typeof b === "undefined" || b === null)
Thus, your function can be rewritten like this :
function a(b,c) {
if (typeof(b) === "undefined" || b === null) { b = 1; }
if (typeof(c) === "undefined" || b === null) { c = 2; }
...
}
This would account for any of undefined
, null
or void 0
passed as arguments. If you find that repetitive, you can always define a utility function :
function exists(obj) {
return typeof(obj) === "undefined" || obj === null;
}
And this precise test is what Coffee-script does with its existential operator ?
. Coffee-script offers default arguments as well, which would make your life even easier.
not sure why you say there's no undefined...
a(undefined, 3)
is what you want
本文标签: Javascript default argumentsonly passing the secondStack Overflow
版权声明:本文标题:Javascript default arguments, only passing the second - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744307756a2599881.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论