我改变了这个:
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
到处都是。这就是我提出问题的原因:
- Why
JSON.parse
解释一个undefined
作为字符串,拖曳如说MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse,“语法错误”undefined
?
- 那么,我应该在解析值之前检查该值是否是正确的字符串?
- 不应该 JSON.parse,每当解析的值是时检查
undefined
然后返回undefined
? (这可能会引起争论,所以,如果你认为这很好,请忽略这个问题或声明我只是错了我的低谷序列)
- 如果#2 是肯定的,那么只需添加一些条件作为第一个片段就足够了,对吧?或者我应该转到调用 MangaElt 的函数并确保
obj.listChaps
是一个数组,忘记吧JSON.parse
这里?。 (这始终是一个数组 http://pastebin.com/niQ6qG0P或字符串中的伪数组,由于这是一个协作项目,因此有人可能有这样做的原因)
对于好奇的人可能会问,“您遇到的错误是什么?”这是:
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
这就是现有条目的样子 https://i.stack.imgur.com/p52OB.png,这不会产生错误。这个场景 https://i.stack.imgur.com/pahVw.png这就是我提出问题的动机。密钥的类型始终相同并事先经过测试:
-
name
是一个字符串
-
mirror
是一个字符串
-
url
是一个字符串
-
listChaps
是字符串内的“数组”
-
ts
and upts
是整数
BTW, obj
是一个物体,但我认为它几乎不可能被错过。另外,这是一个 Chrome 扩展,但我认为这不相关。完整脚本here https://github.com/AllMangasReader-dev/AMR/blob/develop/js/MangaElt.js.