在javascript中,如何区分没有参数传递和未定义参数传递

in javascript, how to distinguish between no arg passed and undefined arg passed

本文关键字:参数传递 未定义 何区 javascript      更新时间:2023-09-26

在函数中,如何区分非参数和未定义的参数?

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);

我相信没有跨浏览器兼容的方法可以做到你想要的。此外,我认为当显式传递undefined时(与根本不传递相比)改变其行为的函数令人困惑。也就是说,您可以通过稍微更改协议来实现总体目标。

让我们检查一下如何使用my_func:

my_func(1) // case A
my_func(1, undefined) // case B
my_func(1, {}.b) // case B
my_func(1, "blah") // case C

明白我的意思吗?只有当调用者传递单个参数时,情况A才会发生。

因此,如果你把my_func()分成两个函数:my_funcA,接受一个参数,my_funcBC,接受两个参数,你将能够正确地实现你的逻辑。

这对函数的调用者造成的唯一变化是,如果调用者传递一个参数,他需要调用my_funcA()。在所有其他情况下,应该调用my_funcBC()

 function my_funcA(a) {
   my_funcBC(a, anotherFunc);
 }
 function my_funcBC(a, b) {
   if (b === undefined) 
     throw( 'INTERNAL ERROR: undefined passed' );
   if (typeof b != 'function') { ... }     
   ...
 }