在一个函数中,如何区分非参数和未定义的参数?
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
中捕获案例 A 和 案例 B 的正确方法是什么?
最佳答案
尝试这样的事情:
function myFunc() {
var a, b;
if (arguments.length === 1) {
a = arguments[0];
console.log('no b passed');
}
else if (arguments.length > 1) {
a = arguments[0];
b = arguments[1];
if (b === undefined) {
console.log('undefined passed as parameter');
}
}
console.log(a, b);
}
myFunc(1);
myFunc(1, undefined);
关于javascript - 在javascript中,如何区分没有传递arg和传递未定义的arg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7750577/