Javascript: 字符串比较返回 true,尽管字符串不同 (间歇性问题)

huangapple go评论78阅读模式
英文:

Javascript: String comparison returns true although the strings are different (intermittent issue)

问题

我正在使用WritableStream以块的方式处理数据。解码后的数据是一个JSON字符串,如果以,开头,我需要删除逗号。

但问题在于,当块被解码为字符串后,我会检查第一个字符

const startsWithComma = chunk.at(0) === ',';

有时它会返回true,尽管块并不以,开头,这会导致后续的JSON.parse失败。请参见附加的图片。

我尝试过的方法:

  • 使用.at()的替代方法,如.charAt().startsWith()chunk[0]

问题是间歇性的,意味着有时它可以处理整个数据,有时可能会在中途失败。

Javascript: 字符串比较返回 true,尽管字符串不同 (间歇性问题)

英文:

I'm processing the data in chunks using WritableStream. The decoded data is a json string and in case it starts with , I need to remove the comma.

But here's the problem, after the chunk is being decoded to string I'm checking the first character

const startsWithComma = chunk.at(0) === ','

and SOMETIMES it returns true although the chunk doesn't start with , and causes the JSON.parse to fail later on. See the attached image.

Things I tried:

  • used .at() alternatives like .charAt(), .startsWith(), chunk[0]

The issue is intermittent meaning sometimes it can process the entire data and sometimes might fail mid through.

Javascript: 字符串比较返回 true,尽管字符串不同 (间歇性问题)

答案1

得分: 1

所以,扩展我的评论:

从你的图片来看,是否有可能在逗号被移除之后才运行调试?也有可能这个块可能以多于1个逗号开头,所以有时在这个确切位置进行调试仍然会显示一个逗号?

解决方案是使用类似以下的 while 循环去掉逗号:

while (chunk.at(0) === ',') {
  chunk = chunk.slice(1).trim();
}

现在我不知道如果 isFirstChunk 而做这个的原因,所以我会不管它,但上面的循环应该解决你的 startsWithComma 问题 Javascript: 字符串比较返回 true,尽管字符串不同 (间歇性问题)

英文:

so, expanding on my comment:<br>
> from your image, is it possible that the debug is running after the comma was already taken out? is it also possible that the chunk may begin with more than 1 comma so sometimes debugging at that exact spot would still show a comma?

The solution would be to take off the commas using a while loop such as

while( chunk.at(0)===&#39;,&#39; ){
  chunk = chunk.slice(1).trim();
}

now I do not know the reason for doing it if isFirstChunk so I'd leave that alone, but the above loop should solve your startsWithComma issue Javascript: 字符串比较返回 true,尽管字符串不同 (间歇性问题)

huangapple
  • 本文由 发表于 2023年1月6日 20:36:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75031026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定