user3268216
user3268216

Reputation: 71

Accessing a associative array

Im trying to create a function that allows us to enter a persons name and their age. It will then be saved into an array.

var personnes=[];

function ajoutePersonne(n,a){
    personnes["Nom"]=personnes.push(n);
    personnes["Age"]=personnes.push(a);
    personnes["Enfant"]=""; 
}
ajoutePersonne("Julie",100);
ajoutePersonne("Sarah",83);
ajoutePersonne("Jennifer",82);
ajoutePersonne("Olivia",79);
ajoutePersonne("Marge",55);
ajoutePersonne("Mathilde",48);
ajoutePersonne("Joanne",45);
ajoutePersonne("Isabelle",47);
ajoutePersonne("Celine",23);
ajoutePersonne("Caroline",29);
ajoutePersonne("Wendy",24);
ajoutePersonne("Kaliste",26);
ajoutePersonne("Karine",22);
ajoutePersonne("Sophie",28);
ajoutePersonne("Orianne",25);
ajoutePersonne("Alice",21);

print(personnes[1].Nom);

How come when im trying to access the 2 second person in the array under the category "Nom", Nothing shows up.

Upvotes: 0

Views: 56

Answers (3)

Christoph
Christoph

Reputation: 51191

Arrays are only meant to store numeric indices, you can create members like Nom but these will in no way react like a normal numeric index.*

Either use an object, or push objects into your array.

var personnes=[];
personnes.push({ "Nom" : "Julie", "Age" : 100 });
personnes[0].Nom // -> Julie

or

var personnes={};
personnes["Julie"] = 100;
// equal to:
personnes.Julie = 100;

or

var personnes={};
personnes["Julie"] = {"age":100 /*,"more attributes":"here"*/}

However, the last two notations assume that the names are unique!

*You can do the following:

var ar = [];
ar.attr = 5;
ar.attr; // -> 5
ar.length; // -> 0, since attr is not enumerable
// also all other regular array operation won't affect attr

Upvotes: 0

KJ Price
KJ Price

Reputation: 5964

personnes is an array, so in javascript it can only have integer indexes.

To do what I think you want to do:

function ajoutePersonne(n,a){
    var person = {nom: n, age: a, enfant: ""};
    personnes.push(person);
}

Where "person" is a javascript object using JSON.

Upvotes: 0

dave
dave

Reputation: 64657

You need to put an entire object in the array, not push the name and age seperately:

var personnes=[];

function ajoutePersonne(n,a){
    personnes.push({ "Nom" : n, "Age" : a, "Enfant" : ""});
}

Upvotes: 2

Related Questions