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

1 komentar:

  1. If the guess on purple is not interesting, possibly it is price making an attempt 1xbet a different guess. A 'break up' is a guess on two adjacent numbers on the roulette table, corresponding to 0 and 00. Slot machine producers don’t simply fabricate slot machines and development sport themes. These world companies include different business segments for lottery, online gaming, and casino operating software and hardware options. They present casino central servers together with the software algorithm which remotely controls all slot machines in that casino. Only 6% probability to win would imply slots machines can be a historic oddity few would remember.

    BalasHapus