英文:
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]
问题是间歇性的,意味着有时它可以处理整个数据,有时可能会在中途失败。
英文:
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.
答案1
得分: 1
所以,扩展我的评论:
从你的图片来看,是否有可能在逗号被移除之后才运行调试?也有可能这个块可能以多于1个逗号开头,所以有时在这个确切位置进行调试仍然会显示一个逗号?
解决方案是使用类似以下的 while 循环去掉逗号:
while (chunk.at(0) === ',') {
chunk = chunk.slice(1).trim();
}
现在我不知道如果 isFirstChunk
而做这个的原因,所以我会不管它,但上面的循环应该解决你的 startsWithComma
问题
英文:
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)===',' ){
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论