JavaScript 中类似 Python 的解包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7077651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:53:17  来源:igfitidea点击:

Python-like unpacking in JavaScript

javascriptunpack

提问by Kit

I have the following string

我有以下字符串

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

Then I JSON.parseit

那我JSON.parse

my_args = JSON.parse(output_string)

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

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

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?

是否有一个核心的 JavaScript 习语可以做到这一点?

回答by fbuchinger

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:

一旦你在一个数组中收集了函数参数,你就可以使用apply()函数对象的方法来调用你预定义的函数:

   some_javascript_function.apply(this, my_args)

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

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

回答by ifedapo olarewaju

You can achieve that by doing this some_javascript_function(...my_args)

你可以通过这样做来实现 some_javascript_function(...my_args)

This is called spreadoperation (as unpackingis in python). view docs here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

这称为spread操作(就像unpacking在 python 中一样)。在此处查看文档https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

回答by joshuakcockrell

Unpack using "..."

使用“...”解包

The same way you accept unlimited args, you can unpack them.

与接受无限参数的方式相同,您可以解压缩它们。

let vals = [1, 2, 'a', 'b'];

console.log(vals);    // [1, 2, "a", "b"]
console.log(...vals); // 1 2 "a" "b"

Example: Accept unlimited arguments into a function

示例:在函数中接受无限参数

It will become an array

它会变成一个数组

const someFunc = (...args) => {
    console.log(args);    // [1, 2, "a", "b"]
    console.log(args[0]); // 1
    console.log(...args); // 1 2 "a" "b"
}

someFunc(1, 2, 'a', 'b');

Example: Send array of arguments into a function

示例:将参数数组发送到函数中

const someFunc = (num1, num2, letter1, letter2) => {
    console.log(num1);    // 1
    console.log(letter1); // "a"
}

let vals = [1, 2, 'a', 'b'];
someFunc(...vals);

Send arguments

发送参数