Javascript 字符串比较 == 有时会失败

2022-01-25 00:00:00 string compare 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
}

相关文章