javascript - 在javascript中,如何区分没有传递arg和传递未定义的arg

标签 javascript function syntax arguments

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

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/

相关文章:

javascript - focus() 在 colorbox 弹出窗口中不起作用

javascript - Angular .js :68 Uncaught Error: [$injector:unpr] Unknown provider: pendingRequestsProvider <- pendingRequests <- $http <- $templateRequest <- $compile

matlab - 缩进会影响 Matlab 代码吗?

Python 名称错误

javascript - react 汉堡菜单 onclick

javascript - Angular2 Google 饼图可视化

javascript - 当调用内部函数时 Firebug 崩溃

c - 使用 C 函数对两个矩阵求和会出现逻辑错误

python - 返回调用此函数的函数

c++ - 如何从多个函数调用中抛出异常一直返回到 main?