在javascript中,如何区分未传递参数和未定义参数传递
在函数中,如何区分非参数和未定义的参数?
myFunc( 'first' );
var obj = { a: 123 };
myFunc( 'first', obj.b );
_or_
myFunc( 'first', undefined )
可以使用 arguments.length
引用过去命名参数的参数,因此没有帮助arguments.length
- 抱歉脑子放屁了!
function myFunc( a, b ) {
// Case A: if no second arg, provide one
// should be: if( arguments.length < 2 ) ...
if( b === undefined ) b = anotherFunc;
// Case B: if b is not resolved - passed but undefined, throw
else if( b === undefined ) throw( 'INTERNAL ERROR: undefined passed' );
// Case C: if b not a function, resolve by name
else if( typeof b != 'function' ) { ... }
...
}
在 myFunc
中捕获 Case A 和 Case B 的正确方法是什么?
within a function, how to discern between a non-arg and an undefined arg?
myFunc( 'first' );
var obj = { a: 123 };
myFunc( 'first', obj.b );
_or_
myFunc( 'first', undefined )
Can be solved easily with arguments.length
refers to arguments past the named arguments, so it's no helparguments.length
- sorry about the brain fart!
function myFunc( a, b ) {
// Case A: if no second arg, provide one
// should be: if( arguments.length < 2 ) ...
if( b === undefined ) b = anotherFunc;
// Case B: if b is not resolved - passed but undefined, throw
else if( b === undefined ) throw( 'INTERNAL ERROR: undefined passed' );
// Case C: if b not a function, resolve by name
else if( typeof b != 'function' ) { ... }
...
}
What is the correct way to capture Case A and Case B in myFunc
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试类似的方法:
Try something like:
我相信没有跨浏览器兼容的方法可以完全满足您的要求。此外,我认为当显式传递未定义(与根本不传递)时改变其行为的函数是令人困惑的。也就是说,您的总体目标可以通过稍微改变协议来实现。
让我们看看您希望如何使用 my_func:
明白我的观点了吗?仅当调用者传递单个参数时,情况 A 才会发生。
因此,如果将
my_func()
分成两个函数:my_funcA
(采用单个参数)和my_funcBC
(采用两个参数),您将能够正确地实现你的逻辑。这对函数的调用者造成的唯一变化是,如果调用者传递单个参数,他需要调用
my_funcA()
。在所有其他情况下,应调用my_funcBC()
。I believe there's no cross-browser compatible way to do exactly what you wish. Moreover, I think that a function that changes its behavior when
undefined
is passed explicitly (vs. not passed at all) is confusing. That said, your overall target can be achieved by slightly changing the protocol.Let's examine how you want my_func to be used:
See my point? Case A can happen only if the caller passes a single argument.
Thus, if you separate
my_func()
into two functions:my_funcA
, taking a single argument, andmy_funcBC
, taking two arguments, you will be able to implement your logic correctly.The only change that this inflicts, on the caller of the function, is that if the caller passes a single argument he needs to call
my_funcA()
. In all other casses,my_funcBC()
should be called.