Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

unpack - Python-like unpacking in JavaScript

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...