使用变量作为对象索引

Cra*_*ide 0 javascript variables object

我正在尝试找到如何将变量作为对象索引传递,例如:

function createObject(index,value){
  var data = {index:value};
  console.log(data);
}

createObject('hello','world');

//result Object { index="world"} instead of Object { "hello"="world"}
Run Code Online (Sandbox Code Playgroud)

到目前为止我找不到这个具体的答案..

谢谢!

Den*_*nis 7

您可以使用object[index]符号:

function createObject(index,value){
    var data = {};
    data[index] = value;
    console.log(data);
}
Run Code Online (Sandbox Code Playgroud)