DrStrangeLove
DrStrangeLove

Reputation: 11557

JS object undefined problem

<script type="text/javascript">
var X = {
   a: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}],
   b: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}],
   c: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}],
   d: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}]


}

var str = JSON.stringify(X);
alert(str);


</script>

What's wrong with this object?? It alerts "Uncaught ReferenceError: john is not defined" How come??

Upvotes: 1

Views: 780

Answers (3)

McStretch
McStretch

Reputation: 20645

You need quotes around john. Otherwise it is referring to an variable/object that has not been created:

var X = {
  a: [{name:"john", phone:777},{name:"john", phone:777},{name:"john", phone:777}]
...

Your code would be valid if john was previously defined:

var john = "john";
var X = {
  a: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}]
  ...

Now john is a variable representing the string "john", and the JSON is valid.

Upvotes: 8

jswidget
jswidget

Reputation: 1

Change X like below. The object attribute names should be single or double quoted. String value should be quoted as well.

var X = {
   a: [{"name":"john", "phone":777},{"name":"john", "phone":777},{"name":"john", "phone":777}],
...
};

Upvotes: 0

kapa
kapa

Reputation: 78671

Try name: 'john', you want it to be a string.

If you simply write john, it will be interpreted as a lookup for a variable (including possibly a function) named john. Since it finds no variable with that name, it will say it is not defined.

Same will go with phone, if the value can be something like 123-456-78 (would be interpreted as 123 minus 456 minus 78). If there can be only numbers, your solution is fine as it is now, otherwise use '123-456-78'.

Upvotes: 5

Related Questions