Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  128] [ 4]  / answers: 1 / hits: 19710  / 13 Years ago, tue, august 16, 2011, 12:00:00

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?


More From » unpack

 Answers
51

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.


[#90590] Sunday, August 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierceabnerc

Total Points: 430
Total Questions: 92
Total Answers: 102

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;