0

I am working on a backbone app, and was provided some sample code, the provider made the data into a for loop which generates a number, I don't want that. I need to enter in player names like Kobe, Lebron etc not player_1, player_2.

//generate 20 players
for(var i=1; i <= 20; i++) {
    players.add({
        id: i,
        name: 'player_' + i,
        score: Math.floor((Math.random()*20)+20)
    });
}

//generate 4 teams, and assign players to them at the same time...
for(var i=1; i <= 4; i++) {
    teams.add({
        id: i,
        name: 'team_' + i,
        players: new App.Collections.Players(players.filter(function(player) {
          return (player.id <= i*5 && player.id > (i-1)*5);
        }))
    });
}

I am not sure how I can turn this into a static piece so I can enter player names manually (name: mike, name: john) not that format of course but I dont want (name: player_1, name: player_2).

I console.logged teams.toJSON() I get the objects in the console, but I cant figure out how to get the raw JSON data so I can see how to structure a hardcoded JSON array.

6
  • Loop an array of names instead of just numbers? Commented Nov 28, 2013 at 3:35
  • That did cross my mind, but I am pretty new to javascript, and I am not sure how to create an array of names then implement it into the loop... This could have been the question itself, but I wouldn't mind writing it statically. I am open to all solutions, if you could kindly provide a sample maybe a fiddle, post it as an answer then I can award you. Commented Nov 28, 2013 at 3:37
  • names=['mike','john']; for (var i=0; i<names.length; i++) .... Same as any other language that has these basic constructs. Commented Nov 28, 2013 at 3:41
  • oh hmm let me try it :) thanks. Commented Nov 28, 2013 at 3:42
  • 1
    I'd suggest you take a tour of JavaScript basics here jqfundamentals.com/chapter/javascript-basics. Don't mean to sound rude, but I'm not sure how you work with Backbone without a basic understand of arrays... Commented Nov 28, 2013 at 3:59

1 Answer 1

2

from your comments what i understood is, you need to write

names=['mike','john'];
for(var i=0; i < names.length; i++) {
    players.add({
        id: i,
        name: 'player_' + names[i],
        score: Math.floor((Math.random()*20)+20)
    });
}

just like other languages you have to give index number to get particular element from array.

Sign up to request clarification or add additional context in comments.

1 Comment

i updated the answer, in initial code i starts with 1 but array indexes starts with 0 so i changed the loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.