如何对 tokenRewards 数组中的 uint 值求和?

How can I sum the uint values ​inside the tokenRewards array?

我想获得我从这个函数中获得的每个令牌获得的奖励数量的总和 getCurrentTotalStakeEarned.

    uint256 public tokensPerBlock;
    mapping(address => uint256) public _balances;
    mapping(address => mapping(uint256 => uint256)) public _ownedTokens;

    function getCurrentTotalStakeEarned(address targetAddress) external view returns (uint256[] memory, uint256[] memory) {
        uint256 [] memory tokenIds = new uint256[](_balances[targetAddress]); 
        uint256 [] memory tokenRewards = new uint256[](_balances[targetAddress]); 
        for(uint256 i = 0; i < _balances[targetAddress]; i++){
            tokenIds[i] = _ownedTokens[targetAddress][i];
            tokenRewards[i] = _getTimeStaked(tokenIds[i]++).mul(tokensPerBlock);
        }
        return (tokenIds, tokenRewards);
    }

    function _getTimeStaked(uint256 tokenId) internal view returns (uint256) {
        if (receipt[tokenId].stakedFromBlock == 0) {
            return 0;
        }

        return block.number.sub(receipt[tokenId].stakedFromBlock);
    }

有了数组,我可以看到每个令牌给我多少。但我想总结一下。

image 我只想把我标红的值求和

我们想要什么?

每个地址的奖励总价值。

我们有什么?

getCurrentTotalStakeEarned

返回的每个地址的奖励数组

我们可以简单地迭代数组并对值求和。

function reduce(uint256[] arr) pure internal returns (uint256 result){
    for (uint256 i = 0; i < arr.length; i++) {
        result += arr[i];
    }
 
    return;
}