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

wet*_*osh 1 javascript

学习功能,当我尝试将键作为参数时,无法理解它们为什么会中断.将值设为参数但不是键时,它们工作正常.关于破解这个问题的JavaScript或jQuery我不知道什么?

例:

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

box('200px', '200px', 500, 'width');
Run Code Online (Sandbox Code Playgroud)

如果我删除第4个参数r,它工作正常.但是在键/值对中创建键的操作不起作用.教我,互联网.

Vis*_*ioN 5

在object literal中,所有键都标识为字符串.要将变量用作JS对象的键,请使用方括号表示法:

function box(e, a, q, r) {
    var config = {
        height : a
    };
    config[r] = e;

    $("div").animate(config, q);
}
Run Code Online (Sandbox Code Playgroud)

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