繁体   English   中英

减少到 Object 错误:无法创建属性

[英]Reduce to Object error: cannot create property

我正在尝试使用数组的 function 输入和回调创建 object。

它没有按预期工作

 function arrToObj(array, callback) { return array.reduce((acc, currStr) => { return acc[currStr] = callback(currStr) }, {}) } const arrOfStrings = ['str1', 'str2']; const capitalize = str => str.toUpperCase(); console.log(arrToObj(arrOfStrings, capitalize)); // expecting: {str1: STR1, str2: STR2}

我收到一个错误:第 4 行的类型错误:无法在字符串“STR1”上创建属性“str2”

我觉得在 reduce 中我从根本上错过了一些东西。 我感谢任何见解,以加深我的知识。

问题在于您的reduce function。 你最后没有返回acc

 function arrToObj(array, callback) { return array.reduce((acc, currStr) => { acc[currStr] = callback(currStr); return acc; }, {}) } const arrOfStrings = ['str1', 'str2']; const capitalize = str => str.toUpperCase(); console.log(arrToObj(arrOfStrings, capitalize)); // expecting: {str1: STR1, str2: STR2}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM