最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
如果你正在使用angularjs,你可以使用angular。Extend,与$的效果相同。jquery的扩展。
var newObj = {};
angular.extend(newObj, ['a','b','c']);
其他回答
如果可以使用Map或Object。分配,很简单。
创建一个数组:
const languages = ['css', 'javascript', 'php', 'html'];
下面的代码创建了一个以index为键的对象:
Object.assign({}, languages)
在地图上复制上面相同的操作
转换为基于索引的对象{0:'css'}等…
const indexMap = new Map(languages.map((name, i) => [i, name] ));
indexMap.get(1) // javascript
转换为一个基于值的对象{css: 'css是伟大的'}等…
const valueMap = new Map(languages.map(name => [name, `${name} is great!`] ));
valueMap.get('css') // css is great
我会使用下划线,但如果没有的话我会使用reduce,初始值为空对象{}
>>> ['a', 'b', 'c'].reduce(function(p, c, i) {p[i] = c; return p}, {})
Object { 0="a", 1="b", 2="c"}
reduce应该在今天的大多数浏览器中广泛使用,参见MDN
更面向对象的方法:
Array.prototype.toObject = function() {
var Obj={};
for(var i in this) {
if(typeof this[i] != "function") {
//Logic here
Obj[i]=this[i];
}
}
return Obj;
}
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
使用javascript简化很简单:
["a", "b", "c", "d"].reduce(function(previousValue, currentValue, index) {
previousValue[index] = currentValue;
return previousValue;
},
{}
);
你可以看看Array.prototype.reduce(), https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce