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

Jac*_*Dev 0 javascript variables jquery function

说我有这个代码:

function helloWorld() {
    console.log(helloText);
}
Run Code Online (Sandbox Code Playgroud)

当我调用这个函数时,我想做这样的事情:

helloWord(
    helloText = "some example text";
)
Run Code Online (Sandbox Code Playgroud)

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

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

helloWorld("some example text");
Run Code Online (Sandbox Code Playgroud)

哪个会起作用,但有一个较长的变量列表,这会变得难以处理.那么我怎样才能通过使用其名称来改变变量值呢?

Eud*_*ran 5

Javascript中没有关键字参数.为了模仿这种行为,你可以使用一个对象文字,如下所示:

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

helloWord({
    helloText: "some example text"
});
Run Code Online (Sandbox Code Playgroud)

  • 这个问题有点难以理解,但这正是他正在寻找的(关键字参数). (2认同)