Halaman

Kamis, 24 Februari 2011

[shared] javascript function with flexible parameters

for example, in ruby i can write a method like this:
def certain_method *args
  "name: " + args[0..1].join(' ') + "\noccupation: " + args[2..-1].join(' ')
end

certain_method 'aya', 'hirano', 'the', 'best', 'seiyuu', 'in', 'the', 'world'
# -> "name: aya hirano\noccupation: the best seiyuu in the world"

but how to do it in javascript?

we can use function's arguments for that.
arguments object is a local variable within all functions.

You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to the argument as: arguments[0], arguments[1], arguments[2]

more detailed article can be seen here:
https://developer.mozilla.org/en/JavaScript/Reference/functions_and_function_scope/arguments

ok, now for the above ruby method, the js function with equal behavior should be something like this:
function certainMethod(like, usual, you, can, define, any, parameters, here) {
    var argsArr = $(arguments).get(); // convert arguments to array
    
    return 'name: ' + argsArr.slice(0, 2).join(' ') + "\noccupation: " + argsArr.slice(2).join(' ');
    
    // first params (like) equal with arguments[0]
}

Demo

Tidak ada komentar:

Posting Komentar