【问题标题】:how can a non empty string .charAt(0) return an empty string?非空字符串 .charAt(0) 如何返回空字符串?
【发布时间】:2021-04-07 13:29:39
【问题描述】:

我真的被这个搞糊涂了……太不可思议了,我发了一张 Chrome 调试器的屏幕截图:

我很快在测试中编写了这个函数来比较 2 个 base64 编码的字符串(a 可能比b 短)。 但是它总是返回 0,就好像第一个字符不同一样。 实际上它们是:字符串a 的第一个字符ca 是正确的,但是由于某种神秘的原因,字符串b 的第一个cb 是空的!字符串 b 看起来正确,长度正确(685 个字符)并且类型正确 typeof(b) == 'string'

调用代码(实际上是 TypeScript)是这样的,以防万一:

requestGET('qBandConfig.sql', { jobid: this.job.jobid }) // get the blob from db 
    .then(json => {
      const base64:string = json[0]['bandconfig'] // type enforced to make sure
      this.editor.setBands(base64)
        .then(() => {
          // test that we find the same blob when re-encoding
          const check:string = this.editor.getBandsBLOB()
          const diff = firstDiff(check, base64) // always return 0 ????
          if (diff > -1 && check[diff] !== '=')
            this.log.warning('encoded blob ', check, ' is different from decoded ', base64)
        })
    })

【问题讨论】:

  • 我们应该在屏幕截图中找到问题吗?比较调试器中的值,提取一个失败的最小集合并将它们发布在这里,检查任何“不可见”的 unicode 字符(console.log([...a.slice(0,2)])),...

标签: javascript string charat


【解决方案1】:

它可能包含不可打印的字符,例如 Zero Width Space,在 HTML 中称为 ​。我不确定 Chrome 开发工具在这种情况下会显示什么;它可能确实什么也没显示。

检查cb.length,如果为0,则cb为空,否则不为空(显然),然后您可以使用charCodeAt()找出其中的内容。

零宽度空格字符的示例代码:

var x = "​";
console.log("x === '" + x + "'");
console.log("x.length === " + x.length);
console.log("x.charCodeAt(0) === " + x.charCodeAt(0));

【讨论】:

  • 就是这样,非常感谢! b.charCodeAt(0) 返回 65520 ...不知道为什么,因为字符串来自数据库的第 3 方包,我希望 Chrome 调试器至少显示一个豆腐,但至少谜团已经消失了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 2014-11-08
  • 2020-01-27
  • 2020-07-11
  • 2015-05-25
  • 2011-05-09
  • 1970-01-01
相关资源
最近更新 更多