简体   繁体   中英

Simple syntax for setting a property in JavaScript on all objects

I'm writing a simple JavaScript game that uses an object to represent a set of teams with scores and other values for the current game as well as previous games. The object will look something like this:

var leaderboard = [
    {team:"Black", captain:"Sparrow", score: 100, treasureFound: 500, totalTreasure: 5000, wins: 2},
    {team:"Blue", captain:"Smollett", score: 5, treasureFound: 0, totalTreasure: 200,  wins: 1},
    {team:"Green", captain:"Hook", score: 10000, treasureFound: 4500, totalTreasure: 25000,  wins: 10}
];

What I'd like to do is reset the score values after each game while persisting the running total values for the session. One way to do this would be with a loop, but I'm wondering if there's a cleaner way to do this without explicitly looping through each team to set all the scores to the same value of 0. Any thoughts?

Here's a fiddle for it: http://jsfiddle.net/2gbgkLg3/1/

Edit : the original question text referenced looking for a non-iterative syntax, but I think this was confusing and distracted from what I was really asking, so I altered it.

You could use forEach (which will iterate through the original array)

leaderboard.forEach(function(record) {
  record.score = 0;
  record.treasureFound = 0;
  record.totalTreasure = 0;
});

You could use a map function (which will create a new array)

leaderboard = leaderboard.map(function(record) {
  record.score = 0;
  record.treasureFound = 0;
  record.totalTreasure = 0;
  return record;
});

So yes, both of these are iterative. But you're working with an array of data so presumably it's a variable amount of records. There's really no other way to do this.

If you know you'll always have 3 teams, you could do this

leaderboard[0].score = 0;
leaderboard[0].treasureFound = 0;
leaderboard[1].score = 0;
leaderboard[1].treasureFound = 0;
leaderboard[2].score = 0;
leaderboard[2].treasureFound = 0;

But your leaderboard will break as soon as you have more than 3 teams — the 4th team's stats will not be reset.

It's more code and looks stupid when a simple loop could be used.


A final option would be to use something like jQuery's $.extend to perform a deep merge.

$.extend(true, leaderboard, [
  {score: 0, treasureFound: 0},
  {score: 0, treasureFound: 0},
  {score: 0, treasureFound: 0}
]);

However, this will fail again as soon as you have more or less than 3 team entries on the leaderboard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM