『奇妙写法』数组组装对象

1,447 阅读1分钟

1. 这样一个问题?

这么一个简单数组[a, b, c, d, e...],通过这个数组组装出一个对象?

可能用这个对象实现一个hash映射,也或许是其它用处

2. 常规解法

创建对象使用for循环遍历

const arr = [a, b, c, d, e]

const obj: any = {}

for(const i of arr) {
    obj[i] = 'sth'
}

3. 优雅解法

使用reduce,MDN参考 Array.prototype.reduce()

const arr = [a, b, c, d, e]

const obj = arr.reduce((res, i) => {
    res[i] = 'sth'
}, {})

// 摘自github出名项目

哈哈,这个方法一下子就充分利用的reduce的特性,简直小聪明呢^O^

4. 想想其它

使用foreach

const arr = [a, b, c, d, e]

const obj:any = {}
arr.forEach(i => {
   res[i] = 'sth'
})

但多了一个obj的定义