如果排除对象类型,如何删除并将后面的函数参数移动到左侧? [英] How do I delete and move later function arguments to the left if an object type is excluded?

查看:65
本文介绍了如果排除对象类型,如何删除并将后面的函数参数移动到左侧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果已经回答,我道歉。我不知道这个方法有更好的技术术语,我似乎无法在这里找到或谷歌搜索。

I apologize if this has already been answered. I don't know a better technical term for this method and I can't seem to find here or Google searches.

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

Basically what I want is to be able to make a function like how jQuery handles Ajax function arguments. Example: $.get(url, callback); and $.post(url, data, callback);

基本上,如果从函数中排除数据,它将移动回调在左边的位置。因为函数运行时它使用输入顺序中的变量名。我假设这个方法涉及检查参数[1] 参数[2] 但是我想确定这是正确的方法,因为我希望我的代码尽可能干净。

Basically if data is excluded from the function it will move callback to the left in its place. Since when the function runs it uses the variable names from the input order. I presuming this method would involve checking the arguments[1] and arguments[2] but I want to make sure if this is the correct way since I like to have my code clean as possible.

推荐答案

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

After spending time using the helpful information here. I managed to code up my solution. I'd thought I post my working (simplified edit) result for those that want a good example how to make one.

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...
}

这篇关于如果排除对象类型,如何删除并将后面的函数参数移动到左侧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆