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
3 Answers
Reset to default 8You 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
版权声明:本文标题:javascript - JS object undefined problem - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745188072a2646777.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论