由于我对JS的了解不佳,在这里我将不胜感激...
我有这个数组:
segments = [
{ state: 33, color: "red" },
{ state: 66, color:"yellow" },
{ state: 100, color: "green" }
]
三个变量:
goal = 100
currentValue = 26
percentage = currentValue * 100 / goal
我正在尝试编写一个比较对象中的百分比和状态的函数,并返回该状态所伴随的颜色。例如:
如果百分比<33,则应返回“红色”。
如果百分比在33到66之间,则必须返回“ yelow”。
如果百分比是> 66或>目标,则必须返回“绿色”。
到目前为止,我有这个,但它不起作用:
defineChartColor = (currentActivity, goal) => segments.find(segments => segments.state > percentage).color
答案 0 :(得分:2)
您需要检查state
,而不是value
对象的<=
。等号对于找到精确的值很重要,例如100
的最后一个。
var segments = [{ state: 33, color: "red" }, { state: 66, color:"yellow" }, { state: 100, color: "green" }],
goal = 100,
currentValue = 26,
percentage = currentValue * 100 / goal,
getColor = (percentage, goal) => segments.find(({ state }) => percentage === goal
? state === 100
: percentage <= state
).color;
console.log(getColor(33, 100));
console.log(getColor(66, 100));
console.log(getColor(100, 100));
console.log(getColor(20, 20));