【问题标题】:Need help to understand a react-native code that uses reduce() on an array需要帮助来理解在数组上使用 reduce() 的 react-native 代码
【发布时间】: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


    【解决方案1】:

    将此当前联系人附加到与其首字母匹配的键上:

      [firstLetter]: [...(obj[firstLetter] || []), contact],
    

    例如,

    {a: ['user a1', 'user a2'] }
    

    所以,

    [a]: [...(['user a1', 'user a2'] || []), 'user a3']
    

    那么,

    [a]: ['user a1', 'user a2', 'user a3']
    

    [已编辑]

    obj 是之前的值。它的第一个值是像这样设置的初始值

    const initialValue = 10;
    [1,2,3].reduce((prev, current) => prev + current, initialValue)
    // 10 + (1+2+3) = 16
    

    在您的情况下,obj 初始值为 {}

    【讨论】:

    • 非常感谢我现在明白这部分了,但是你知道我的第一个问题的答案吗?为什么我们可以在reduce 中传递objreduce 的语法只有传递 currentValue 参数而不传递 obj ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多