admin管理员组

文章数量:1415664

<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 e??

<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 e??

Share Improve this question asked May 11, 2011 at 12:11 DrStrangeLoveDrStrangeLove 11.6k16 gold badges63 silver badges73 bronze badges 2
  • 9 john needs to be in quotes as it is a string not a variable identifier – meouw Commented May 11, 2011 at 12:12
  • 3 @meouw You should have made that an answer instead of a ment+1 – user657496 Commented May 11, 2011 at 12:14
Add a ment  | 

3 Answers 3

Reset to default 8

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.

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'.

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}],
...
};

本文标签: javascriptJS object undefined problemStack Overflow