使用变量作为对象索引

时间:2013-10-04 12:29:02

标签: 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"}

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

谢谢!

3 个答案:

答案 0 :(得分:7)

您可以使用object[index]表示法:

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

答案 1 :(得分:0)

如果我理解你想要的那就是代码

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

createObject('world');

答案 2 :(得分:0)

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

createObject('hello', 'world');