javascript(es6)返回forEach中filter的值

问题描述 投票:2回答:1

我的功能如下。

如果过滤器的值是一个大于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;
    });
  };
javascript reactjs ecmascript-6
1个回答
2
投票

您可以通过检查长度来过滤密钥

const getHitedShips = () => {
    const { players } = this.props;
    return Object
        .keys(players)
        .filter(key => players[key].ships.filter(ship => ship.health <= 0).length >= 5);
};
© www.soinside.com 2019 - 2024. All rights reserved.