采用以下标记:
<div data-player-id="1" data-points="8">Player 1</div>
<div data-player-id="1" data-points="8">Player 1</div>
<div data-player-id="2" data-points="5">Player 2</div>
<div data-player-id="2" data-points="5">Player 2</div>
<div data-player-id="3" data-points="6">Player 3</div>
我想做的是合并每个data-player-id
的点。
所以我的想法是迭代 data-player-id
并为每个玩家创建一个对象,如下所示:
const points = [];
document.querySelectorAll('[data-player-id]').forEach((element) => {
const player = {
id: element.getAttribute('data-player-id'),
points: element.getAttribute('data-points'),
}
// Combine all players with the same "id"
points.push(player);
});
我遇到的问题是合并具有相同 id
的所有对象。
它不一定是一个对象,如果使用数组更好,我很乐意沿着这条路走下去。
最佳答案
您可以使用reduce
您可以为其提供初始值。这里我使用了一个对象,玩家 id 是键,属性值是点。我还在元素上使用了解构来从数据集中获取 id 和点值,而不是使用 getAttribute
。
const els = document.querySelectorAll('[data-player-id]');
const points = [...els].reduce((acc, element) => {
// Destructure the id and points from the dataset of the element
const { dataset: { playerId, points } } = element;
// If the id doesn't exist in the object create it
// and set it to zero
acc[playerId] = acc[playerId] || 0;
// Add the new points to the total for that id
// making sure you convert the string to a number
acc[playerId] += +points;
return acc;
}, {});
console.log(points);
<div data-player-id="1" data-points="8">Player 1</div>
<div data-player-id="1" data-points="8">Player 1</div>
<div data-player-id="2" data-points="5">Player 2</div>
<div data-player-id="2" data-points="5">Player 2</div>
<div data-player-id="3" data-points="6">Player 3</div>
关于javascript - 根据玩家ID累加玩家总积分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57697872/