<script type="text/javascript">
var X = {
a: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}],
b: [{name:john, phone:777},{nam开发者_如何学Goe: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??
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}],
...
};
精彩评论