最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
如果你正在使用jquery:
$.extend({}, ['a', 'b', 'c']);
其他回答
如果你正在使用jquery:
$.extend({}, ['a', 'b', 'c']);
这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行
const nodes = {
node1: {
interfaces: {if1: {}, if2: {}}
},
node2: {
interfaces: {if3: {}, if4: {}}
},
node3: {
interfaces: {if5: {}, if6: {}}
},
}
解决方案是结合使用reduce和对象扩展:
const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})
快速和肮脏的#2:
var i = 0
, s = {}
, a = ['A', 'B', 'C'];
while( i < a.length ) { s[i] = a[i++] };
如果可以使用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
我将使用Array.of()简单地做到这一点。Array of有能力使用它的context作为构造函数。
注2:of函数是一个有意通用的工厂方法;它 不要求它的this值是数组构造函数。 因此,它可以传递给其他构造函数或由其他构造函数继承 可以使用单个数值参数调用。
因此,我们可以将array .of()绑定到一个函数,并生成类似object的数组。
虚函数(){}; var thingy = Array.of.apply(dummy,[1,2,3,4]); console.log(页面);
通过使用array .of(),甚至可以进行数组子类化。