[英]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?? 它警告“Uncaught ReferenceError:john未定义”怎么来?
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: 如果以前定义了john
,您的代码将是有效的:
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. 现在john
是一个表示字符串“john”的变量,JSON是有效的。
Try name: 'john'
, you want it to be a string. 试试name: 'john'
,你希望它是一个字符串。
If you simply write john
, it will be interpreted as a lookup for a variable (including possibly a function) named john
. 如果您只是编写john
,它将被解释为查找名为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). 如果值可以是123-456-78
(将被解释为123减去456减去78),那么同样会使用phone
。 If there can be only numbers, your solution is fine as it is now, otherwise use '123-456-78'
. 如果只有数字,你的解决方案就像现在一样好,否则使用'123-456-78'
。
Change X like below. 改变X如下。 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}],
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.