我正在为以下任务寻找一个很好的方法:我有一个回合游戏。在每一轮中,我们有一个介于1-10之间的数字。
到目前为止,我就是这样做的,但我被困住了。
gameValues.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
我想数我的数组中的双主菜,但我只想注意最后5轮。
Round 6 ( We already have 5 values ):
gameValues = [9,9,9,2,1]
result: 9:3, 2:1, 1:1,
Round 7 ( Now we have 6 values but I only want to count the first 5):
gameValues = [3,9,9,9,2,1]
result: 3:1, 9:3, 2:1,
我不能只数过去5轮。
发布于 2021-05-27 12:18:12
在遍历数组之前,您可能需要对其进行切片。
gameValues.slice(-5).forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
发布于 2021-05-27 12:18:52
使用gameValues.slice(-5)
获取数组的最后5个值,然后执行相同的计数操作:
gameValues = [3,9,9,9,2,1]
counts = {}
gameValues.slice(-5).forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
console.log(counts);
// { '1': 1, '2': 1, '9': 3 }
发布于 2021-05-27 12:17:57
您可以使用接合获取数组中的最后5个数字,然后使用reduce获取每个数字的计数。
splice()方法通过移除或替换现有元素和/或添加新元素来更改数组的内容。若要在不修改数组的情况下访问数组的一部分,请参见片()。
function countLastFive(arr) {
return arr.splice(-5).reduce((acc, curr) => {
acc[curr] = acc[curr] ? ++acc[curr] : 1;
return acc;
}, {});
}
console.log(countLastFive([9, 9, 9, 2, 1, 3, 1]));
console.log(countLastFive([9, 9, 9, 2, 1]));
console.log(countLastFive([3, 9, 9, 9, 2, 6, 4, 3, 2, 1]));
只需确保切片更改原始数组即可。所以最好克隆这个数组,这样它就不会改变原始的数组
function countLastFive(arr) {
return arr.splice(-5).reduce((acc, curr) => {
acc[curr] = acc[curr] ? ++acc[curr] : 1;
return acc;
}, {});
}
const arr1 = [9, 9, 1, 9, 2, 1];
const arr2 = [9, 9, 1, 9, 2, 1];
console.log("Before -> arr1 => ", arr1);
console.log(countLastFive(arr1));
console.log("After -> arr1 => ", arr1);
console.log("Before -> arr2 => ", arr2);
console.log(countLastFive([...arr2]));
console.log("After -> arr2 => ", arr2);
https://stackoverflow.com/questions/67721851
复制相似问题