简体   繁体   English

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

[英]Reduce to Object error: cannot create property

I'm trying to create an object with a function inputs of an array and a callback.我正在尝试使用数组的 function 输入和回调创建 object。

It's not working as intended它没有按预期工作

 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}

I'm getting an error: Type Error on line 4: Cannot create property 'str2' on string 'STR1'我收到一个错误:第 4 行的类型错误:无法在字符串“STR1”上创建属性“str2”

I feel like there is something I've missed fundamentally with reduce.我觉得在 reduce 中我从根本上错过了一些东西。 I appreciate any insights to further my knowledge.我感谢任何见解,以加深我的知识。

The issue is in your reduce function.问题在于您的reduce function。 You are not returning the acc at the end.你最后没有返回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.

相关问题 JS reduce: TypeError: Cannot create property at Array.reduce - JS reduce: TypeError: Cannot create property at Array.reduce 动态 object 键...无法在字符串上创建属性 - Dynamic object keys… Cannot create property on string GSAP“无法在编号上创建属性”错误 - GSAP “Cannot create property on number” error MongoDB错误:无法在字符串上创建属性“ _id” - MongoDB Error: Cannot create property '_id' on string 无法读取属性“#” <Object> 的不确定错误? - Cannot read property '#<Object>' of undefined getting error? 错误类型错误:无法删除 [object Array] 的属性“1” - ERROR TypeError: Cannot delete property '1' of [object Array] 无法减少对象内部的数组 - Cannot reduce array inside of an object 如何使用多个定界符将字符串简化为自定义对象,未捕获(承诺):TypeError:无法读取未定义的属性 - How to reduce a string into a custom object using several delimiters, Uncaught (in promise): TypeError: Cannot read property of undefined 通过属性对象将对象数组减少到总计 - Reduce array of object to totals by property object 如果对象为 null(“无法读取属性”错误),则无法检查 null - Cannot check for null if the object is null ("cannot read the property" error)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM