Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

javascript - Parameter destructuring (equivalent of python's double-splat)

In python I can pass a dict whose keys match parameters' names with the ** (double-splat) operator:

def foo(a, b):
    print (a - b)

args = {'b': 7, 'a': 10}

foo(**args) # prints 3

How to do the same in ES6? This doesn't work:

function foo(a, b) {
    console.log(a - b)
}

args = {b: 7, a: 10}

foo(...args)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to do the same in ES6?

There are no named arguments in JS, only positional ones. So the answer is: you can not.

What you can do is either emulate named arguments via object passing, as @Andy suggested.

function foo({ a, b }) {
    console.log(a - b);
}

let args = { b: 7, a: 10 };

foo(args);

Or you could make args to be an array, so you can destruct it into positional arguments.

function foo(a, b) {
    console.log(a - b);
}

let args = [10, 7];

foo(...args);

Okay-okay, just for the sake of the argument: it is possible to write a function that will extract parameters of foo and yield properties of args in required order.

function * yolo(args, fn) {
    const names = fn.toString().match(/(.+)/)[0]
                    .slice(1, -1).split(',')
                    .map(x => x.trim());

    while (names.length) {
        yield args[names.shift()];
    }
}

function foo(a, b) {
    console.log(a - b);
}

const args = { b: 7, a: 10 };

foo(...yolo(args, foo));

I would not dare to use it in production though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...