最好的转换方式是什么:

['a','b','c']

to:

{
  0: 'a',
  1: 'b',
  2: 'c'
}

当前回答

ES5 -解决方案:

使用数组原型函数“push”和“apply”,你可以用数组元素填充对象。

Var arr = ['a','b','c']; var obj = new Object(); Array.prototype.push。应用(obj, arr); console.log (obj);// {'0': 'a', '1': 'b', '2': 'c', length: 3} console.log (obj [2]);/ / c

其他回答

一个快速而肮脏的问题:

var obj = {},
  arr = ['a','b','c'],
  l = arr.length; 

while( l && (obj[--l] = arr.pop() ) ){};

如果你正在使用jquery:

$.extend({}, ['a', 'b', 'c']);

更面向对象的方法:

Array.prototype.toObject = function() {
 var Obj={};

 for(var i in this) {
  if(typeof this[i] != "function") {
   //Logic here
   Obj[i]=this[i];
  }
 }

 return Obj;
}

快速和肮脏的#2:

var i = 0
  , s = {}
  , a = ['A', 'B', 'C'];

while( i < a.length ) { s[i] = a[i++] };

这是一个解决方案在coffeescript

arrayToObj = (arr) ->
  obj = {}
  for v,i in arr
    obj[i] = v if v?
  obj