在我的JavaScript游戏中,我将分数保存在多维数组中(在本地存储中)。
我要保存themeID
,这是已播放主题的标识符。此外,我还要保存游戏设置(pieces
和shapesSquare
)和游戏的duration
。
我现在需要比较分数以找到每种设置的最佳分数(=高分)。在这种情况下,最佳分数表示持续时间值最低(请随意忽略持续时间的格式,因为我知道如何比较时间戳,只需将其视为常规数字即可。)
对我来说,关键点是只比较不同的设置,然后找到最低的持续时间值。我不需要整个阵列的最短持续时间,而是需要为每个设置找到它。这意味着我需要找出themeID
,pieces
和shapesSquare
的相同之处来比较分数。如果pieces
或shapesSquare
不同,那么此themeID
的得分应该是不同的。
对我来说,理想的结果是为每个主题设置一个数组,并设置“最佳”分数。
数组如下:
let scores = [
{
"themeID": 1,
"pieces": 10,
"shapesSquare": true,
"duration": "00:01:00"
},
{
"themeID": 1,
"pieces": 10,
"shapesSquare": true,
"duration": "00:01:30"
},
{
"themeID": 4,
"pieces": 20,
"shapesSquare": false,
"duration": "00:04:00"
},
{
"themeID": 4,
"pieces": 30,
"shapesSquare": true,
"duration": "00:03:20"
}
]
顺便说一下,scores
数组非常灵活,因为我是自己创建的,因此,如果您有任何更改结构的建议(使其更易于迭代),请随时告诉我
在此先感谢您的帮助!
答案 0 :(得分:0)
我会尝试:
const minMaxDurationMap = new Map();
for (const score of scores) {
const key = JSON.stringify([score.themeID,score.pieces,score.shapesSquare]);
const minMax = minMaxDurationMap.get(key);
if (minMax) {
if (score.duration < minMax.min) minMax.min = score.duration;
else if (score.duration > minMax.max) minMax.max = score.duration;
} else {
minMaxDurationMap.set(key, { min: score.duration, max: score.duration });
}
}
顺便说一句,我认为您应该将持续时间存储为数字(秒或毫秒)而不是字符串。
我对解决方案的密钥生成不满意,但是我无法提出更好的解决方案。