【发布时间】:2026-02-04 16:40:01
【问题描述】:
什么是最好的转换方式
['a', 'b', 'c', 'd', 'e', 'f']
进入:
{
"a": "b",
"c": "d",
"e": "f"
}
【问题讨论】:
-
你有没有尝试过或者有一些代码可以给我们看?
标签: javascript arrays
什么是最好的转换方式
['a', 'b', 'c', 'd', 'e', 'f']
进入:
{
"a": "b",
"c": "d",
"e": "f"
}
【问题讨论】:
标签: javascript arrays
如何使用旧的 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())
【讨论】:
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());
【讨论】: