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

标签 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");

这可以工作,但是如果变量列表较长,就会变得笨拙。那么我怎样才能通过使用变量的名称来更改变量值呢?

最佳答案

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

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

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

关于javascript - 调用函数时如何按名称设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28140638/

相关文章:

javascript - 如何根据下拉菜单选择值预填表单?

javascript - 具有正确签名的通用函数

sql - ORACLE SQL ORA-22814 属性或元素值大于指定类型

javascript - parse.com - 限制谁可以注册

javascript - 如果用户的互联网连接中断,如何提醒用户

javascript - if 语句仅适用于第一个实例

jquery - 未捕获的类型错误 : Cannot set property 'unobtrusive' of undefined

javascript - 在谷歌地图上使用 80,000 个标记加快页面速度

javascript - extjs中的颜色转换

javascript - 用 js 函数 window.history.back() 添加一个参数