Python-like unpacking in JavaScript

前端 未结 3 405
遇见更好的自我
遇见更好的自我 2020-12-05 10:17

I have the following string

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

Then I JSON.parse it

m         


        
相关标签:
3条回答
  • 2020-12-05 10:34

    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.

    0 讨论(0)
  • 2020-12-05 10:34

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

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

    0 讨论(0)
  • 2020-12-05 10:35

    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

    0 讨论(0)
提交回复
热议问题