调用函数时如何按名称设置变量?

时间:2015-01-25 19:37:35

标签: javascript jquery function variables

说我有这段代码:

function helloWorld() {
    console.log(helloText);
}

当我调用此函数时,我想做类似的事情:

helloWord(
    helloText = "some example text";
)

当然不起作用。但我的想法是,我想通过在调用该函数时引用它的名称来更改变量。我看到很多jQuery幻灯片和这样做的东西,但我似乎无法弄明白。我能找到的最接近的是:

function helloWorld(helloText) {
    console.log(helloText);
}

helloWorld("some example text");

哪个会起作用,但是如果变量列表较长,则会变得难以处理。那么我怎样才能通过使用其名称来改变变量值?

2 个答案:

答案 0 :(得分:5)

Javascript中没有关键字参数。为了模仿该行为,您可以使用对象文字,如下所示:

function helloWorld(args) {
    console.log(args.helloText);
}

helloWord({
    helloText: "some example text"
});

答案 1 :(得分:2)

基于其他答案ECMAScript 6 introduces destructuringdefault parameters。这使您可以轻松模拟关键字参数:

function helloWorld({helloText} = {}) {
    console.log(helloText);
}

helloWord({
    helloText: "some example text"
});

您现在可以将ES6功能与预处理器一起使用,例如6to5