首页 > 解决方案 > 如何在地图函数中返回一个对象(React.js)

问题描述

我有一些用户输入,我需要将它们拆分为字符,然后只使用 map 将字符数组和索引数组作为对象返回。尝试了很多方法,但都失败了。希望我能在这里得到一些帮助。我是 react.js 的新手,我的代码可能听起来很笨拙。代码在 App.js 中是主要组件。

  charList = () => { 
    this.state.userInputs.split("").map((ch1, index1) => 
    { return {ch: ch1, index: index1}
    } ); 
  }

我希望能够访问这两个数组的 this.charList.ch 和 this.charList.index。不确定我是否清楚地描述了我的问题。提前致谢。

标签: reactjs

解决方案


如果你想要这样的东西:

[
  { "ch": "h", "index": 0 },
  { "ch": "i", "index": 1 }
]

你只是错过了一个return以前this.state.userInputs.split("")

charList = () => { 
    return this.state.userInputs.split("").map((ch1, index1) => {
        return {ch: ch1, index: index1 }
    })
}

推荐阅读