【发布时间】:2020-05-13 03:01:03
【问题描述】:
这段代码来自一个简单的 React Native Contacts 应用程序,它应该使用reduce 方法来:
对于数组contacts中的每个联系人,提取第一个字母并将其大写,然后return一个对象,该对象维护对象的所有先前键并将此当前联系人附加到与其第一个字母匹配的键。
//contacts 是一个对象数组 {key, name, phone}
const contactsByLetter = props.contacts.reduce((obj, contact) => {
const firstLetter = contact.name[0].toUpperCase()
return {
...obj,
[firstLetter]: [...(obj[firstLetter] || []), contact],
}
}, {})
reduce 语法是arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
首先,我看不到obj 参数在语法中的位置。其次,我了解扩展符号的工作原理,但我没有特别了解整个返回部分[...(obj[firstLetter]
代码在这个文件SectionListContacts file,整个代码here
【问题讨论】:
标签: javascript arrays react-native