Is there a way to provide named parameters in a function call in JavaScript?

前端 未结 10 1726
抹茶落季
抹茶落季 2020-11-22 07:28

I find the named parameters feature in C# quite useful in some cases.

calculateBMI(70, height: 175);

What can I use if I want this in JavaS

10条回答
  •  逝去的感伤
    2020-11-22 07:31

    There is another way. If you're passing an object by reference, that object's properties will appear in the function's local scope. I know this works for Safari (haven't checked other browsers) and I don't know if this feature has a name, but the below example illustrates its use.

    Although in practice I don't think that this offers any functional value beyond the technique you're already using, it's a little cleaner semantically. And it still requires passing a object reference or an object literal.

    function sum({ a:a, b:b}) {
        console.log(a+'+'+b);
        if(a==undefined) a=0;
        if(b==undefined) b=0;
        return (a+b);
    }
    
    // will work (returns 9 and 3 respectively)
    console.log(sum({a:4,b:5}));
    console.log(sum({a:3}));
    
    // will not work (returns 0)
    console.log(sum(4,5));
    console.log(sum(4));
    

提交回复
热议问题