Pass an arbitrary number of parameters into a JavaScript function

前端 未结 3 969
猫巷女王i
猫巷女王i 2021-01-13 04:02

My JavaScript code is barely an Ajax request that expects XML to be returned from back-end. The back-end can return execute_callback as one of XML tags like thi

相关标签:
3条回答
  • 2021-01-13 04:43

    Instead of calling the function, reference your function as an element in an associative array by name:

    var funcName = // parse your xml for function name
    var params = new Array();
    params[0] = 10.2; // from your parsed xml
    params[1] = 'some text'; // also from your parsed xml
    
    // functions are attached to some Object o:
    
    o[funcName](params); // equivalent to o.funcName(params);
    

    I wrote an example of the above here: http://jsbin.com/ewuqur/2/edit

    0 讨论(0)
  • 2021-01-13 04:45

    You could refer to Function.apply. Assuming the callback functions are declared in global object (window in browser).

    var callback_function = window[function_name];
    if (callback_function) { // prevent from calling undefined functions
        callback_function.apply(window, params);  // params is an array holding all parameters
    }
    
    0 讨论(0)
  • 2021-01-13 05:01

    You can just pass them all into your function:

    function someFunction(){
        for(i = 0; i < arguments.length; i++)
            alert(arguments[i]);
    }
    

    Javascript functions have an arguments array-like object, and it is syntactically correct to call a javascript function with any number of arguments.

    someFunction(1, 2, 'test', ['test', 'array'], 5, 0);
    

    is a valid call to that function.

    0 讨论(0)
提交回复
热议问题