0

i'm trying to create object named client. and put it into a array. And after this, read the name of the 1st client.

Exemple :

client1 {nom : "marco", prenom : "chedel", adresseMail : "ssss@ggg.com"};

and put this client into an array like bellow.

listClients[client1]

what i did :

var listClients = [];
var client1 = {nom : "chedel",prenom:"Marco",adresseMail:"marco@gmail.com"};
listClients.push(client1);
var client2 = {nom : "De Almeida",prenom:"Jorge",adresseMail:"jorge@gmail.com"};
listClients.push(client2);


function afficheClients(tableau){
  for (i=0;i<tableau.length;i++)
    {
      var c = tableau[i];
      document.write(c[adresseMail]); 
     // This ^^ doesn't work, it says :adresseMail isn't definied in c
    }
}

afficheClients(listClients);
e1che
  • 1,241
  • 1
  • 17
  • 34
  • 1
    First: Don't use `document.write`. Second: you have a syntax error. Try `c.addresseMail` instead of `c[addresseMail]` – Nick Husher Oct 01 '13 at 15:17
  • 1
    The issue was that `adresseMail` didn't have string delimiters around it ie. you could use `c["adresseMail"]`. heres a fiddle using jQuery to create list items for each mail address http://jsfiddle.net/kvPWr/. (In the example I use the dot notation) I'd strongly recommend using console.log to view stuff and Chrome DevTools to debug rather than document.write, it'll give you a lot more information that will help solve stuff like this :) – Stephen James Oct 01 '13 at 15:21
  • @NickHusher, i'm using document.write because my professor theaches that way.. what can i use instead ? thx ! – e1che Oct 02 '13 at 08:40
  • `document.write` has a lot of gotchas and is a dangerous language feature to become dependent on. Instead, you could use direct DOM manipulation; [Here's a very simple example](http://jsbin.com/IdAGije/1/edit) (jsbin) – Nick Husher Oct 02 '13 at 13:38

3 Answers3

3

You're treating adressMail as a variable and not as a string:

use

document.write(c["adresseMail"]); 
bitoiu
  • 6,893
  • 5
  • 38
  • 60
2

There are two ways to access properties of an object:

obj.prop
obj['prop']

You are doing the following mixture which doesn't work: obj[prop].

Fix your code to c.adresseMail or c['adresseMail'] and it will work.

Tibos
  • 27,507
  • 4
  • 50
  • 64
2

Either reference it using a string:

document.write(c['adresseMail']);

or using dot notation:

document.write(c.adresseMail);

And, yes - document.write should be avoided.

Andy
  • 61,948
  • 13
  • 68
  • 95