如何使用JavaScript在函数中指定key作为参数

How to specify key as parameter in a function using JavaScript

本文关键字:key 参数 何使用 JavaScript 函数      更新时间:2023-09-26

学习函数,不能理解为什么当我试图将键作为参数时它们会崩溃。当将值作为参数而不是键时,它们工作得很好。我不知道JavaScript或jQuery会破坏这个吗?

的例子:

function box(e, a, q, r) {
    $('div').animate({
        r : e,
        'height' : a
    }, q);
}
box('200px', '200px', 500, 'width');

如果我去掉第四个参数r,它工作得很好。但是关于在键/值对中创建键的一些事情不起作用。教我吧,互联网。

在对象文本中,所有键都被标识为字符串。要使用变量作为JS对象的键,使用方括号表示法:

function box(e, a, q, r) {
    var config = {
        height : a
    };
    config[r] = e;
    $("div").animate(config, q);
}

阅读更多: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId