Pass only the second argument in javascript

前端 未结 2 1332
一生所求
一生所求 2020-12-17 16:01

I try currently to make a function in which I pass only the second argument of my function. I have read some documentation but nothing probing to me.

I would make t

相关标签:
2条回答
  • 2020-12-17 16:08

    With default parameter values added in ES2015, you can declare default values for the parameters, and when making the call, if you pass undefined as the first parameter, it will get the default:

    function test(a = "ay", b = "bee") {
      console.log(`a = ${a}, b = ${b}`);
    }
    test();             // "a = ay, b = bee"
    test(1);            // "a = 1, b = bee"
    test(undefined, 2); // "a = ay, b = 2"
    test(1, 2);         // "a = 1, b = 2"

    You can do something similar yourself manually in a pre-ES2015 environment by testing for undefined:

    function test(a, b) {
      if (a === undefined) {
        a = "ay";
      }
      if (b === undefined) {
        b = "bee";
      }
      console.log("a = " + a + ", b = " + b);
    }
    test();             // "a = ay, b = bee"
    test(1);            // "a = 1, b = bee"
    test(undefined, 2); // "a = ay, b = 2"
    test(1, 2);         // "a = 1, b = 2"

    0 讨论(0)
  • 2020-12-17 16:15

    If you are OK with a change to the number of arguments that your function takes, you could pass the arguments via object properties. Then you can let the caller decide which property (or properties) to specify during the call.

    The other properties can take default values through object destructuring in the function's parameter specification:

    function test({a = 1, b = 2}) {
        console.log(`a = ${a}, b = ${b}`);
    };
    
    test({b:42}); // only specify what b is

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