假设我有这个代码:
function helloWorld() {
console.log(helloText);
}
当我调用这个函数时,我想做这样的事情:
helloWord(
helloText = "some example text";
)
这当然行不通。但我的想法是,我想在调用该函数时通过引用变量的名称来更改变量。我看到很多 jQuery 幻灯片和执行此操作的东西,但我似乎无法弄清楚。我能找到的最接近的是:
function helloWorld(helloText) {
console.log(helloText);
}
helloWorld("some example text");
这可以工作,但是如果变量列表较长,就会变得笨拙。那么我怎样才能通过使用变量的名称来更改变量值呢?
最佳答案
Javascript 中没有关键字参数。为了模仿这种行为,您可以使用对象文字,如下所示:
function helloWorld(args) {
console.log(args.helloText);
}
helloWord({
helloText: "some example text"
});
关于javascript - 调用函数时如何按名称设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28140638/