JSON.parse如何管理'未定义'

How does JSON.parse manage 'undefined'?

本文关键字:未定义 管理 parse 何管理 JSON      更新时间:2023-09-26

我转换了这个:

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。这就是我提出问题的原因:

  1. 为什么JSON.parseundefined解释为字符串,比如MDN;语法错误";对于undefined
  2. 那么,我应该在解析值之前检查该值是否是正确的字符串吗
  3. JSON.parse不应该在解析的值为undefined时进行检查,然后只返回undefined吗?(这可能会引发争论,所以,如果你认为这是好的,就忽略这个问题,或者说我只是错了。)
  4. 如果#2是肯定的,那么仅仅添加一些条件作为第一个剪切就足够了,对吧?或者我应该转到调用MangaElt的函数,并确保obj.listChaps是一个数组,而忽略这里的JSON.parse吗?。(这始终是字符串中的数组或伪数组,由于这是一个协作项目,因此可能有人对此有原因)

好奇的人可能会问:"你犯了什么错误?"这是吗

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

这就是现有条目的样子,它们不会产生错误。这是我提出问题的原因。钥匙的类型总是相同的,并且事先经过测试:

  • name是字符串
  • mirror是字符串
  • url是字符串
  • CCD_ 13是一个";阵列";在绳子里面
  • tsupts为整数

顺便说一句,obj是一个对象,但我认为它几乎是不可能错过的。此外,这是一个Chrome扩展,但我不认为这是相关的。在此处完成脚本。

undefined不是有效的JSON令牌。将未定义的值转换为JSON时,正确的做法是将其呈现为null。

  1. undefined不是JSON文件中的合法令牌(请参见www.JSON.org),也不是JSON.parse可接受的参数
  2. 您的代码在语义上与以前的版本不相同。以前版本中的许多测试比新版本更详尽(也不容易出错)
  3. 如果代码按要求工作,为什么要"重构"代码?你没有重构它——你已经破坏了它