gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:57:49 25 4
gpt4 key购买 nike

这是如何在 JavaScript 中实现的?

function myFunc(arg1, [optionsObject,] callback)

如果缺少 optionsObject,回调将位于第二个位置而不是第三个位置。该函数如何注意到这种情况并进行适当的处​​理?

最佳答案

这不是 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.
}

关于javascript - 函数签名中间的可选参数是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44144439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com