如何将javascript数组转换为对象?

时间:2018-07-13 08:30:07

标签: javascript arrays

什么是最好的转换方式

['a', 'b', 'c', 'd', 'e', 'f']

进入:

{
  "a": "b", 
  "c": "d",
  "e": "f"
}

2 个答案:

答案 0 :(得分:1)

如何使用旧的好for循环并跳过第二个迭代?

 Array.prototype.toObject  = function(){
 // var len = this.length -1; // omit 'e' property
  var len = this.length; // leave 'e' property
 
  var obj = {};
  
  for (var i = 0; i< len; i=i+2){
    obj[this[i]] = this[i+1];
  }
  
  return obj;
}

var arr1 = ['a', 'b', 'c', 'd', 'e']

console.log(arr1.toObject())

答案 1 :(得分:-4)

 Array.prototype.toObject  = function(){
   // var length = this.length - 1;
   return this.reduce(function(obj, val, index, array) {
      if(index %2 != 0) return obj;
      // if(index == length) return obj; // leave the 'e' property
      obj[val] = array[index+1];
      return obj;
   }, {})
 }
 
 
var a = ['a', 'b', 'c','d', 'e', 'f'];
console.log(a.toObject());