简体   繁体   中英

javascript: array with unknown length and unknown index names

I am making a program of a football league.

A example of a league:

team1 team2 team3

I want to save (increase) number of players for each team like

var teamArray = [];
teamArray[team1] = 1;
teamArray[team2] = 2;

and I am doing in the body of some functions like:

function 1(){}
function 2(){}
function .(){}
function .(){}
function .(){}
function n(){}

but this works only when i "teach" javscript that the array is an integer array... with somethin like

teamArray[team1] = 0;
teamArray[team1] = teamArray[team1] + 1;

but the problem is every time when i come to one of my functions, i have to set my array element to 0 and that makes the whole calculation wrong...

Could anyone give me a hint please?

My Idea was to was to set each array element to 0 from the beginning, but i dont know at the beginning of my game how many teams i will have today, that why i implemented the array like:

var teamArray = [];

Use a JavaScript object instead. Something like:

var teamObject = {
   team1: 3,
   team2: 5,
   team3: 7,
};

Or, perhaps an array of objects:

var teamArray = [
   { name: 'team1', players: 3 },
   { name: 'team2', players: 5 },
   { name: 'team3', players: 7 }
];

The object is easier to access if all you want is to get or set the number of players:

teamObject.team1 += 1;

but an array is easier to loop through and can be ordered:

for (var i=0,j=teamArray.length; i<j; i++) {
  console.log(teamArray[i].name + " has " + teamArray[i].players + " players");
}

You can increment the number of team members by testing the current number first, and if it does not exist, you initialise it with 0 on the fly. All that can be done in one expression with a logical OR ( || ):

 teamArray[team1] = (teamArray[team1] || 0) + 1;

This will not destroy the previous value you had and work like a simple + 1 in that case.

You should define your teamArray as object, although it will work with array as well (since that is an object as well):

 teamArray = {}

The name is then of course a bit confusing, but I'll stick with it.

Whenever you need to iterate over the teams you have collected, then you can use a for loop like this:

for (var team in teamArray) {
    console.log(team, teamArray[team]);
}

thanks for all your help!

I did it like this now:

var listItems = $("#teamsDropdown li");
    listItems.each(function(idx, li) {
        var team = $(li).text();
        TeamPlayerQuantities[team] = 0;             
    });

and increasing the qnty of players wiht functions like:

function1(team){
    TeamPlayerQuantities[team] ++;
}

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