Javascript String Compare == sometimes fails

后端 未结 9 2017
你的背包
你的背包 2020-12-05 17:25

How could the following code sometimes evaluate to false?

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

M

相关标签:
9条回答
  • 2020-12-05 17:58

    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.

    0 讨论(0)
  • 2020-12-05 18:00

    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.

    0 讨论(0)
  • 2020-12-05 18:02

    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.

    0 讨论(0)
  • 2020-12-05 18:03
    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!
    
    0 讨论(0)
  • 2020-12-05 18:04

    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")
    
    0 讨论(0)
  • 2020-12-05 18:15

    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.

    0 讨论(0)
提交回复
热议问题