javascript(es6)forEach中过滤器的返回值

时间:2018-09-05 19:30:39

标签: javascript reactjs ecmascript-6

我具有如下功能。

如果过滤器的值是一个大于4的数组,我只想返回键。

例如const result = gethitedShips(); // result be 1 or 2,但我得到undefined

我完全困惑在哪里返回什么

    getHitShips = () => {
    const { players } = this.props;
    return Object.keys(players).forEach(key => {
      const hitShips = players[key].ships.filter(ship => ship.health <= 0);
      if (hitShips.length >= 5) return key;
      return null;
    });
  };

1 个答案:

答案 0 :(得分:2)

您可以通过检查长度来过滤键

const getHitedShips = () => {
    const { players } = this.props;
    return Object
        .keys(players)
        .filter(key => players[key].ships.filter(ship => ship.health <= 0).length >= 5);
};