JavaScript中类似Python的解压缩 [英] Python-like unpacking in JavaScript

查看:63
本文介绍了JavaScript中类似Python的解压缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串

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

然后我JSON.parse

my_args = JSON.parse(output_string)

如何以类似Python的方式将其解压缩,以使my_args中的每个元素都成为JavaScript函数的参数?

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])

有没有做到这一点的核心JavaScript习惯?

Is there a core JavaScript idiom that does that?

推荐答案

一旦您将函数参数收集到数组中,就可以使用函数对象的apply()方法来调用其预定义函数:

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)

第一个参数(this)设置被调用函数的上下文.

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

这篇关于JavaScript中类似Python的解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆