FPS Example
Here's an example of using the every()
method in the context of a first-person shooter game:
Let's say we have an array of objects representing the players in a multiplayer game, with each object containing properties like the player's username, level, and rank. Here's an example of such an array:
const players = [
{ username: "player1", level: 30, rank: "Gold" },
{ username: "player2", level: 20, rank: "Silver" },
{ username: "player3", level: 40, rank: "Platinum" },
{ username: "player4", level: 50, rank: "Diamond" }
];
Now, let's say we want to check whether all the players in the game have a rank of "Gold" or higher. We can use the every()
method to do this by calling every()
on the players
array and passing a function that checks the rank
property of each object. Here's how we could do this:
const allGoldOrHigher = players.every(player => player.rank === "Gold" || player.rank === "Platinum" || player.rank === "Diamond");
console.log(allGoldOrHigher); // Output: false
In this example, every()
returns false
because not all players have a rank of "Gold" or higher. If we wanted to check whether all players have a level of 30 or higher, we could modify the callback function like this:
const allLevel30OrHigher = players.every(player => player.level >= 30);
console.log(allLevel30OrHigher); // Output: true
In this case, every()
returns true
because all players have a level of 30 or higher.
Last updated