我是新来的反应和lodash。我正在尝试将一些数据四舍五入到小数点后两位。

selectedPlayers {
0: {SHOT__Goals: 1.222222}
1: {SHOT__Goals: 0.888888}
}

 const goals = ( selectedPlayers ) => {
 const goal= _.round((selectedPlayers.SHOT__Goals), 2).toFixed(2);
 return goals;
 }


SHOT__Goals以未定义的形式出现,我如何引用它,以便知道在selectedPlayers内部查找

我希望它返回1.22和0.88之类的值

最佳答案

实际上,您不需要lodash,可以使用Array.prototype.map函数:



const selectedPlayers = [{ SHOT__Goals: 1.222222 }, { SHOT__Goals: 0.888888 }];

const goals = selectedPlayers => selectedPlayers.map(player => player.SHOT__Goals.toFixed(2));

console.log(goals(selectedPlayers))





但是,对于我收集的内容,您实际上并不希望goals是一个函数,但是如果我没错,那么结果数组将执行以下操作:



const selectedPlayers = [{ SHOT__Goals: 1.222222 }, { SHOT__Goals: 0.888888 }];

const goals = selectedPlayers.map(player => player.SHOT__Goals.toFixed(2));

console.log(goals)





注意事项:


我将selectedPlayers转换为数组,更易于操作
我不太明白为什么还有_.round时为什么要使用toFixed

10-06 02:47