我改造了这个:
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
对象中的所有值,因此,我希望到处都有一些 undefined
。这就是我提出问题的原因:
- 为什么
JSON.parse
将undefined
解释为字符串,如 MDN ,undefined
的“语法错误”? - 那么,我是否应该在解析值之前检查该值是否是正确的字符串?
- 不应该 JSON.parse,只要解析的值是
undefined
就检查并返回undefined
吗? (这可能会引起争论,所以,如果您认为这很好,请忽略这个问题或声明我只是错了我的波谷序列) - 如果#2 是肯定的,那么只需添加一些条件作为第一个片段就足够了,对吧?或者我应该转到调用 MangaElt 的函数并确保
obj.listChaps
是一个数组,而忘记这里的JSON.parse
吗? (This is always an array 或字符串中的伪数组,由于这是一个协作项目,因此有人可能有理由这样做)
好奇的人可能会问,“你得到的错误是什么?”这是:
Error in event handler for 'undefined': Unexpected token u SyntaxError: Unexpected token u
at Object.parse (native)
at new MangaElt (chrome-extension://nhjloagockgobfpopemejpgjjechcpfd/js/MangaElt.js:44:25)
at readManga (chrome-extension://nhjloagockgobfpopemejpgjjechcpfd/js/background.js:410:24)
at chrome-extension://nhjloagockgobfpopemejpgjjechcpfd/js/background.js:607:9
at Event.dispatchToListener (event_bindings:356:21)
at Event.dispatch_ (event_bindings:342:27)
at Event.dispatch (event_bindings:362:17)
at miscellaneous_bindings:165:24
at Event.dispatchToListener (event_bindings:356:21)
at Event.dispatch_ (event_bindings:342:27) event_bindings:346
This is what already existing entries looks like ,这不会产生错误。 This scenario是什么激发了我的问题。键的类型总是相同的,并且事先经过测试:
name
是一个字符串mirror
是一个字符串url
是一个字符串listChaps
是字符串中的“数组”ts
和upts
是整数
顺便说一句,obj
是一个对象,但我认为它几乎不可能被遗漏。此外,这是一个 Chrome 扩展程序,但我认为这不相关。完整脚本 here .
最佳答案
undefined
不是有效的 JSON 标记。将未定义的值转换为 JSON 时,正确的做法是将其呈现为 null。
关于javascript - JSON.parse 如何管理 'undefined' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17648150/