如何将变量用作JavaScript对象的键?

时间:2017-12-22 18:24:15

标签: javascript

我的代码如下:

var currency = "USD";
var value = 100;

function test(currency, value) {
    var myObject = {("" + currency): value};
    console.log(myObject);
}

test(currency, value);

我正在尝试获取如下对象:

{"USD": 100}

如何修复代码才能执行此操作?

2 个答案:

答案 0 :(得分:1)

您可以为该对象选择computed property name



function test(currency, value) {
    return { [currency]: value };
}

var currency = "USD",
    value = 100;

console.log(test(currency, value));




答案 1 :(得分:1)

在javascript中我们可以添加对象:

  • 点符号
  • 方括号

但只有第二种情况允许动态访问/添加属性 -

var currency = "USD";
var value = 100;
var myObject = {};

function test(currency, value) {
  myObject[currency] = value;
  console.log(myObject);
}

test(currency, value);