Javascript 字符串比较 == 有时会失败 [英] Javascript String Compare == sometimes fails

查看:22
本文介绍了Javascript 字符串比较 == 有时会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码有时如何评估为假?

How could the following code sometimes evaluate to false?

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

我的 JavaScript 代码:

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
}

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

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

推荐答案

双等号是 Javascript 中比较字符串的合适方法,它返回 false,那么一个字符串的左右可能有空格.

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.

p>

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

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
}

这篇关于Javascript 字符串比较 == 有时会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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