【问题标题】:Python-like unpacking in JavaScript在 JavaScript 中类似 Python 的解包
【发布时间】:2011-10-28 00:07:08
【问题描述】:

我有以下字符串

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 函数的参数?

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 习惯用法可以做到这一点?

【问题讨论】:

  • @arunkumar, this answer 这个问题看起来很有趣,这使得这个问题略有不同。我们可以为函数参数这样做吗?
  • 我很抱歉,你是对的。它不是重复的。在下面的答案中似乎有一种方法可以做到这一点。我将删除之前的评论,因为它不相关。

标签: javascript unpack


【解决方案1】:

在数组中收集函数参数后,您可以使用函数对象的apply() 方法来调用您的预定义函数:

   some_javascript_function.apply(this, my_args)

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

【讨论】:

  • .apply 效果很好,但.call 并没有完全用Array 参数来实现它。谢谢,您为我指明了正确的方向。这篇 Function apply and function call in JavaScript 的文章看起来很有趣。
  • 请注意,这不适用于console.log.apply(...)。那应该使用console.log.apply(console, arguments)。见this question
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    使用“...”解压

    就像你接受无限的参数一样,你可以解压它们。

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

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

    会变成数组

    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');
    

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

    const someFunc = (num1, num2, letter1, letter2) => {
        console.log(num1);    // 1
        console.log(letter1); // "a"
    }
    
    let vals = [1, 2, 'a', 'b'];
    someFunc(...vals);
    

    发送参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-16
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2011-03-04
      • 1970-01-01
      • 2019-02-04
      相关资源
      最近更新 更多