为什么这两个相同的字符串在JavaScript中不相同?

编程入门 行业动态 更新时间:2024-10-25 18:26:52
本文介绍了为什么这两个相同的字符串在JavaScript中不相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在javascript中使用AJAX时会遇到这个问题。

I encounter this problem when I use AJAX in javascript.

usernameRequest.responseText 的值为ok且类型为 string ,但它不等于字符串'ok'。请告诉我原因,非常感谢!

The value of usernameRequest.responseText is "ok" and the type is string, however it dose not equal to the string 'ok'. Please tell me why, thank you very much!

推荐答案

通常的原因与 == 相比,两个看起来相同但不匹配的字符串是一个或两个包含一些空格或换行符,你不知道这两个字符串字符串不完全相同。

The usual reason for two strings that appear to be the same to not match when compared with == is that one or both contains some whitespace or newlines that you aren't aware of making the two strings not quite identical.

您通常可以通过以下方式对此进行调试:

You can usually debug this by looking at:

console.log("'" + usernameRequest.responseText + "'");

这将让您看到字符串的边界,并查看任何前导或尾随空格甚至换行符确切地看到你有什么以及为什么它可能不匹配。

which will let you see the boundaries of the string and see any leading or trailing whitespace or even newlines to see exactly what you have and why it might not be matching.

你也可以在比较之前修剪字符串上的额外空格:

You can also just trim extra whitespace off the string before comparing like this:

if (usernameRequest.responseText.trim() == "ok")

更多推荐

为什么这两个相同的字符串在JavaScript中不相同?

本文发布于:2023-11-06 09:54:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563371.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这两个   字符串   中不   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!