Javascript:将数组转换为对象的最佳方法是什么?

Javascript:将数组转换为对象的最佳方法是什么?

问题描述:

什么是最好的转换方式:

what is the best way to convert:

a = ['USD', 'EUR', 'INR']

a = {'USD': 0, 'EUR': 0, 'INR': 0};

*将数组元素作为初始值为 0 的对象的键.

*manipulating array element as key of objects with value as initially 0.

使用 Array#reduce 方法来减少到单个对象.

Use Array#reduce method to reduce into a single object.

a = ['USD', 'EUR', 'INR'];

console.log(
  a.reduce(function(obj, v) {
    obj[v] = 0;
    return obj;
  }, {})
)

甚至简单的 for 循环也可以.

Or even simple for loop is fine.

var a = ['USD', 'EUR', 'INR'];
var res = {};

for (var i = 0; i < a.length; i++)
  res[a[i]] = 0;

console.log(res);