如果排除对象类型,如何删除并将后面的函数参数移到左侧

How do I delete and move later function arguments to the left if an object type is excluded?

本文关键字:函数 参数 类型 对象 排除 何删除 删除 如果      更新时间:2023-09-26

如果已经有人回答了,我很抱歉。我不知道一个更好的专业术语来描述这种方法,我似乎在这里或谷歌搜索中找不到。

基本上我想要的是能够使一个函数像jQuery处理Ajax函数参数。示例:$.get(url, callback);$.post(url, data, callback);

基本上,如果data被排除在函数之外,它将把callback移动到它的位置。因为当函数运行时,它使用输入顺序中的变量名。我假设这种方法将涉及检查arguments[1]arguments[2],但我想确保这是正确的方式,因为我喜欢让我的代码尽可能干净。

与其检查参数[1]和参数[2],不如检查

$.post(url, data, callback)

url是否为字符串,数据是否为对象,回调是否为函数

在花时间使用这里的有用信息之后。我设法编写了我的解决方案。我想我张贴我的工作(简化编辑)结果为那些想要一个很好的例子如何使一个。

function post(url) {
    var callback, data, isAsync, // Prepare possible arguments.
        i, // Loop index.
        length = arguments.length; // Get arguments length.
    // Check the argument's types for optional passed parameter options.
    for (i = 1; i < length && i < 4; i++) {
        if (typeof arguments[i] === "object") {
            data = arguments[i];
        }
        if (typeof arguments[i] === "function") {
            callback = arguments[i];
        }
        if (typeof arguments[i] === "boolean") {
            isAsync = arguments[i];
        }
    }
    // Asynchronous is enabled by default.
    if (isAsync === undefined) {
        isAsync = true;
    }
    // More code here...
}