最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Array of objects in Javascript - Stack Overflow

programmeradmin3浏览0评论

I'm new to learning Javascript. at this stage, I want to use/decalre/initialize an array of objects.

Here is my code to initialise an object :

function player(name){
    this.name = name;

    this.getName = function(){
        alert(this.name);
    }
}

and here is where I need to use the array of players(objects)

function hallOfFame(nbrPlayers){
    var arrayOfPlayers = [] 

}

Can anyone help me please how to create this array of objects. Thank you in advance :)

I'm new to learning Javascript. at this stage, I want to use/decalre/initialize an array of objects.

Here is my code to initialise an object :

function player(name){
    this.name = name;

    this.getName = function(){
        alert(this.name);
    }
}

and here is where I need to use the array of players(objects)

function hallOfFame(nbrPlayers){
    var arrayOfPlayers = [] 

}

Can anyone help me please how to create this array of objects. Thank you in advance :)

Share Improve this question edited Feb 28, 2017 at 22:55 baao 73.4k18 gold badges150 silver badges207 bronze badges asked Feb 28, 2017 at 22:54 Hajar ELKOUMIKHIHajar ELKOUMIKHI 923 silver badges11 bronze badges 16
  • What is nbrPlayers? – Justin Taddei Commented Feb 28, 2017 at 22:57
  • Can I show you some easier way to create array of objects? (: – kind user Commented Feb 28, 2017 at 22:58
  • var arrayOfPlayers = [ new player('Elitia'), new player('Mike') ]; See MDN's documentation for more examples. – Heretic Monkey Commented Feb 28, 2017 at 22:59
  • @JustinTaddei : nbrPlayers means the number of objects that I want to use to build my array with. I want to create an array like this in C, arrayOfPlayers[nbrPlayers] – Hajar ELKOUMIKHI Commented Feb 28, 2017 at 22:59
  • 1 arrays don't work like that in javascript they don't e with a size – Noah Reinagel Commented Feb 28, 2017 at 23:00
 |  Show 11 more ments

5 Answers 5

Reset to default 2
function createPlayerArray(number) {
  var players = [];
  for (i = 0; i < number; i++) {
    players.push(new Player("No Name"));
  }
  return players;
}

this will create an array of players

You can do something like the following to create an array of players when instantiating a new HallOfFame. The addPlayer prototype will let you, well, add new players to the array later. In general - you don't need to specify a fixed length for an array in javascript. The size is flexible, so you can just create an empty array to have an array of players, then push onto that.

function Player(name){
    this.name = name;

    this.getName = function(){
        alert(this.name);
    }
}

function HallOfFame(players) {
 	this.players = Array.from(players);
}

HallOfFame.prototype.addPlayer = function(player) {
	this.players = this.players.concat(player);
}


let p1 = new Player("foo");
let p2 = new Player("bar");
let p3 = new Player("baz");

let hOf = new HallOfFame([p1,p2]); // instantiate HallOfFame and add two players

hOf.addPlayer(p3); // add another player

console.log(hOf); // will show you an HallOfFame object holding 3 players

Just for learning purposes, tell me if it's too easy, I will delete it.

var dogs = ['Gustavo', 'Heisen', 'Berg', 'Jessie'],
    race = ['Labrador', 'Doberman', 'Spaniel', 'Husky'],
    result = [];
    
    dogs.forEach(function(v,i){ //iterate over each element from dogs array
      var obj = {}; //create an empty object to store our data
      obj[v] = race[i]; //assign a key (which is name of the dog) and it's value (his race) to obj
      result.push(obj); //push object into the result array
    });                 //repeat! (:
    
    console.log(result); //show our array of objects!

As you're using the player function to create objects, it seems like a good use case for a class declaration, which stated purpose is to "provide a much simpler and clearer syntax to create objects":

class Player {
    constructor(name) {
        function capitalizeName(fullName) {
          return fullName
          .split(' ')
          .map((s) => {
            return `${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()}`
          })
          .join(' ')
        }
        this.name = capitalizeName(name)
    }

    getName () {
      return this.name
    }

    alertName () {
      alert(this.getName())
    }
}

You can then use the map method create an array of Players from an array of strings, like this:

function hallOfFame(playerNames) {
  return playerNames.map((playerName) => new Player(playerName))
}

You can test the function using the forEach method:

> let myPlayerNames = ['ADA', 'bob', 'CaRlA', 'DenniS', 'ElITIa']
> let myHallOfFame = hallOfFame(myPlayerNames)
> myHallOfFame.forEach((player) => player.alertName())
//making array of books
var books = [];
    var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
    books.push(new_book);
    new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
    books.push(new_book);
    console.log(books[0].id);
    console.log(books[0].name);
    console.log(books[0].category);
    console.log(books[0].price);

// also we have array of albums
var albums = []    
    var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
    albums.push(new_album);
    new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
    albums.push(new_album);
//Now, content[0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name); 

console.log(my_albums[0].name);
console.log(my_albums[1].name); 

This Example Works with me: Expected output

发布评论

评论列表(0)

  1. 暂无评论