Javascript 函数签名中间的可选参数是如何实现的?

Javascript 函数签名中间的可选参数是如何实现的?,javascript,Javascript,这是如何在JavaScript中实现的 function myFunc(arg1, [optionsObject,] callback) 如果缺少选项Object,则回调将位于第二个位置,而不是第三个位置。函数如何注意到这种情况并适当地处理它?不是JS在做这件事,而是函数本身,myFunc。通常要做的是获取参数(这是一个包含参数的类似数组的结构)并确定最后一项是什么。如果它是一个函数,将其弹出并将其作为回调。剩下的只是简单的论点 下面是示例代码: function myFunc(){ //

这是如何在JavaScript中实现的

function myFunc(arg1, [optionsObject,] callback)

如果缺少
选项Object
,则回调将位于第二个位置,而不是第三个位置。函数如何注意到这种情况并适当地处理它?

不是JS在做这件事,而是函数本身,
myFunc
。通常要做的是获取
参数
(这是一个包含参数的类似数组的结构)并确定最后一项是什么。如果它是一个函数,将其弹出并将其作为回调。剩下的只是简单的论点

下面是示例代码:

function myFunc(){
  // arguments is usually turned into an array to access array methods
  var args = Array.prototype.slice.call(arguments);

  // Check the type of the last item
  var hasCallback = typeof args[args.length - 1] === 'function';

  // If the last item is a function, it's probably a callback. Pop it off.
  var callback = hasCallback ? args.pop() : function(){};

  // By now, args is your argument list and callback is a function that either
  // does something or is a noop.
}

不是JS在做这件事,而是函数本身,
myFunc
。通常要做的是获取
参数
(这是一个包含参数的类似数组的结构)并确定最后一项是什么。如果它是一个函数,将其弹出并将其作为回调。剩下的只是简单的论点

下面是示例代码:

function myFunc(){
  // arguments is usually turned into an array to access array methods
  var args = Array.prototype.slice.call(arguments);

  // Check the type of the last item
  var hasCallback = typeof args[args.length - 1] === 'function';

  // If the last item is a function, it's probably a callback. Pop it off.
  var callback = hasCallback ? args.pop() : function(){};

  // By now, args is your argument list and callback is a function that either
  // does something or is a noop.
}

类似于第二个参数的
类型
,可能是
“函数”
“对象”
?或者
参数。长度
2
3
。类似于
第二个参数的类型,可能是
“函数”
“对象”
?或者
arguments.length
,即
2
3