簡體   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