Javascript String Compare == 有时会失败

发布于 2024-07-20 07:39:22 字数 619 浏览 7 评论 0原文

为什么下面的代码有时会计算为 false?

(transport.responseText == '1' || 
 transport.responseText == 'CARD_VALID')

我的 JavaScript 代码:

if (transport.responseText == '1' || 
    transport.responseText == 'CARD_VALID') {
    // do something.
}
else if (transport.responseText == 'CARD_INVALID' || 
             transport.responseText == 'INVALID_CHECKSUM') {
    // do something else....
}
else {
    new Ajax.Request('/report_error.php?responseText='+transport.responseText);
    // report error to user
}

当字符串相同时,什么会导致 JavaScript 字符串比较 == 返回 false?

How could the following code sometimes evaluate to false?

(transport.responseText == '1' || 
 transport.responseText == 'CARD_VALID')

My JavaScript code:

if (transport.responseText == '1' || 
    transport.responseText == 'CARD_VALID') {
    // do something.
}
else if (transport.responseText == 'CARD_INVALID' || 
             transport.responseText == 'INVALID_CHECKSUM') {
    // do something else....
}
else {
    new Ajax.Request('/report_error.php?responseText='+transport.responseText);
    // report error to user
}

What could cause JavaScript string compare == to return false when the strings are identical?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

月竹挽风 2024-07-27 07:39:22

Double equals 是在 Javascript 中比较字符串的适当方法,它返回 false,则一个字符串的左侧和/或右侧可能有空格。

.trim() 放在字符串末尾,我的比较应该开始工作:

var panel = response.substr(0, response.indexOf("<")).trim();
if(panel == "combo"){
    //do something
}

Double equals is the appropriate way to compare strings in Javascript, it is returning false then there may be whitespace to the left and or right of one string.

Put a .trim() on the end of the strings and my comparison should started working:

var panel = response.substr(0, response.indexOf("<")).trim();
if(panel == "combo"){
    //do something
}
つ低調成傷 2024-07-27 07:39:22
A1 = "speed"
A2 = "speed" 

if(A1 == A2)  => Error !!!

在控制台中使用此测试:

escape("speed")

结果:“速度”

escape(A1)

结果:“速度%0D”=> 这就是问题%0D!!!

escape(A2)

结果:“速度”=> 好的!!!

使用正确的代码:

if(A1.slice(0, -1) == A2) This is OK!
A1 = "speed"
A2 = "speed" 

if(A1 == A2)  => Error !!!

USE THIS TEST IN CONSOLE:

escape("speed")

result: "speed"

escape(A1)

result: "speed%0D" => This is the problem %0D !!!

escape(A2)

result: "speed" => OK !!!

Use correct code:

if(A1.slice(0, -1) == A2) This is OK!
情场扛把子 2024-07-27 07:39:22

我遇到了一个类似的问题,两个明显相同的字符串不相等,我费尽心思试图解决它,所以我这样做了:

for (var c=0; c<string_1.length; c++) {
    if (string_1.charCodeAt(c) != string_2.charCodeAt(c)) {
        alert('c:'+c+' '+string_1.charCodeAt(c)+'!='+string_2.charCodeAt(c));
        valid = false;
    }
}

我发现一个字符串上的最后一个字符是 10,而一个字符串上的最后一个字符是 10。另一个是 13,我以为两个字符串都是空终止的,但事实并非如此。

I had a similar problem where two obviously identical strings would not be equal, and I was pulling my hair out trying to solve it, so I did this:

for (var c=0; c<string_1.length; c++) {
    if (string_1.charCodeAt(c) != string_2.charCodeAt(c)) {
        alert('c:'+c+' '+string_1.charCodeAt(c)+'!='+string_2.charCodeAt(c));
        valid = false;
    }
}

And I found that the last character on one string was 10, and the last character on the other was 13, I thought both strings were null terminated, but they were not.

埖埖迣鎅 2024-07-27 07:39:22

我遇到了同样的问题,我注意到我正在比较两个对象

在此处输入图像描述

为了解决这个问题,我必须使用

JSON.stringify(user._id) === JSON.stringify(userId) // true 

I had the same problem and i noticed that i was comparing two objects

enter image description here

to solve this issue i had to use

JSON.stringify(user._id) === JSON.stringify(userId) // true 
许仙没带伞 2024-07-27 07:39:22

尝试使用 === 来精确匹配(类型和值)。 这是 javascript 中推荐的比较运算符。

检查字符串的数据类型以确保确定,并在两个字符串中查找隐藏的 unicode 或控制字符。

Try using === to match exactly (type and value). This is the recommended comparison operator in javascript.

Check the datatypes of the strings to make sure, and look for hidden unicode or control characters in both strings.

冬天旳寂寞 2024-07-27 07:39:22

我建议您使用 标准化最好是“NFKC”或“NFKD”,因为它们似乎将不间断空间标准化为常规空间。

所以你可以将代码编写为:-

string1.normalize("NFKC") === string2.normalize("NFKC")

I would advice you to use normalization preferably "NFKC" or "NFKD" as these seem to normalize non-breaking space into regular space.

So you can write your code as :-

string1.normalize("NFKC") === string2.normalize("NFKC")
余生再见 2024-07-27 07:39:22

如果你想要一些不那么复杂的东西并且你正在处理数字值,那么使用

parseFloat()

就像一个魅力

If you want something a little less complicated and you are dealing with NUMERIC VALUES, use

parseFloat()

works like a charm

旧伤还要旧人安 2024-07-27 07:39:22

在进入该代码块之前,尝试将 responseText 的值捕获到不同的变量中,以防变量在其中的某处更新。

我没有太多直接使用 XmlHttpRequest 的经验,但我确实知道 javascript 有很多地方使用对在执行期间可以更改的接口对象的易失性引用,而不是简单的值。

Try capturing the value of responseText into a different variable before entering that code block, in case the variable is updated somewhere in there.

I don't have that much experience directly using XmlHttpRequest, but I do know that javascript has a number of places where it uses volatile references to interface objects that can change during execution, rather than a simple value.

萌能量女王 2024-07-27 07:39:22

选角对我有用

if (timeSlots[j].id + '' == product.timeSlots[k].id + '') {
}

casting worked for me

if (timeSlots[j].id + '' == product.timeSlots[k].id + '') {
}
天涯离梦残月幽梦 2024-07-27 07:39:22

Java servlet 可以发送字符串,即

out.println("CARD_VALID");

out.print("CARD_VALID");

这些在 Javascript 中可能看起来相同,但在第一种情况下末尾有空格。

Java servlet may send strings i.e.

out.println("CARD_VALID");

or

out.print("CARD_VALID");

These may look identical in Javascript, but there are white spaces at the end in the first case.

一刻暧昧 2024-07-27 07:39:22
export const isEqualStr = (str1: any, str2: any): boolean => 
 (str1 + '').trim().toLowerCase() === (str2 + '').trim().toLowerCase();
export const isEqualStr = (str1: any, str2: any): boolean => 
 (str1 + '').trim().toLowerCase() === (str2 + '').trim().toLowerCase();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文