为什么这两个相同的字符串在JavaScript中不相同? [英] Why are these two identical strings not equal in JavaScript?

查看:111
本文介绍了为什么这两个相同的字符串在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中不相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆