Javascript JSON.parse如何管理';未定义';?
我改变了这一点:Javascript JSON.parse如何管理';未定义';?,javascript,json,Javascript,Json,我改变了这一点: function MangaElt(obj) { "use strict"; this.mirror = obj.mirror; this.name = obj.name; this.url = obj.url; if (obj.lastChapterReadURL !== undefined) { this.lastChapterReadURL = obj.lastChapterReadURL; this.lastChapterReadNa
function MangaElt(obj) {
"use strict";
this.mirror = obj.mirror;
this.name = obj.name;
this.url = obj.url;
if (obj.lastChapterReadURL !== undefined) {
this.lastChapterReadURL = obj.lastChapterReadURL;
this.lastChapterReadName = obj.lastChapterReadName;
} else {
this.lastChapterReadURL = null;
this.lastChapterReadName = null;
}
this.listChaps = [];
if (obj.listChaps !== undefined && obj.listChaps !== null && obj.listChaps !== "null") {
if (!isArray(obj.listChaps)) {
this.listChaps = JSON.parse(obj.listChaps);
}
}
this.read = 0;
if (obj.read !== undefined && obj.read !== null && obj.read !== "null") {
this.read = obj.read;
}
}
为此:
function MangaElt(obj) {
"use strict";
this.mirror = obj.mirror;
this.name = obj.name;
this.url = obj.url;
this.lastChapterReadURL = obj.lastChapterReadURL || null;
this.lastChapterReadName = obj.lastChapterReadName || null;
this.listChaps = JSON.parse(obj.listChaps) || [];
this.read = obj.read || 0;
this.update = obj.update || 1;
}
正如您所看到的,代码现在更加可读和紧凑。该代码段在正常情况下工作正常。问题是,我有时没有obj
对象中的所有值,因此,我希望在这里和那里有一些未定义的
。这就是我提出问题的原因:
JSON.parse
将未定义的
解释为字符串,比如说未定义的
的“语法错误”未定义的
,就检查并返回未定义的
?(这可能会引起争论,因此,如果你认为这是好的,那么就忽略这个问题,或者说我只是错了我的槽列)obj.listChaps
是一个数组,而忽略JSON.parse
?。(或者字符串中的伪数组,由于这是一个协作项目,可能有人对此有原因)
是一个字符串name
是一个字符串mirror
是一个字符串url
是字符串中的“数组”listChaps
和ts
是整数upts
obj
是一个对象,但我认为它几乎不可能错过。此外,这是一个Chrome扩展,但我认为这与此无关。完整的脚本
undefined
不是JSON文件中的合法标记(请参见www.JSON.org),也不是JSON.parse的可接受参数
undefined
不是有效的JSON令牌。将未定义的值转换为JSON时,正确的做法是将其呈现为null。奇怪的是,它试图在Google Chrome/ium中将未定义的解析为字符串。需要详细说明吗?@Braiam:JSON.parse将您发送给它的任何内容解释为字符串。它相当于字符串(输入)
,意思是字面true
,false
,25
,将接受null
undefined
不会,因为根据您在其他注释中发布的规范第15.12.1.2节,这不是有效的JSON。1。我查看了这个网站,没有关于如何处理未定义的的参考,也没有在3。在进行更改之前,我使用断点将近一个小时,从未得到未定义
或空
(JSON部分除外)。这就是为什么我认为多余的行是不必要的。那么,想详细说明一下,如果两者有相同的行为,我是如何打破它的吗?2.正如#3,隐式测试是不必要的,所以我使用了更便宜的方法。Alnitak的观点是,未定义
不是一个合法的标记,这就是为什么没有关于如何处理它的参考。它是无效的,所以它的处理方式与任何其他无效输入一样。如果您在响应json代码中确实需要它,那么应该将其作为字符串提供。