Python-like unpacking in JavaScript

Kit picture Kit · Aug 16, 2011 · Viewed 15.6k times · Source

I have the following string

output_string = "[10, 10, [1,2,3,4,5], [10,20,30,40,50]]"

Then I JSON.parse it

my_args = JSON.parse(output_string)

How do I unpack it in a Python-like way so that every element in my_args becomes an argument to a JavaScript function?

some_javascript_function(*my_args)
// should be equivalent to:
some_javascript_function(my_args[0],my_args[1],my_args[2],my_args[3])
// or:
some_javascript_function(10, 10, [1,2,3,4,5], [10,20,30,40,50])

Is there a core JavaScript idiom that does that?

Answer

fbuchinger picture fbuchinger · Aug 16, 2011

Once you 've collected the function arguments in an array, you can use the apply() method of the function object to invoke your predefined function with it:

   some_javascript_function.apply(this, my_args)

The first parameter (this) sets the context of the invoked function.