anybody have an idea what is happening with this i've got the code
console.log('cCP: '+chatCurrentPlace+' - key: '+key);
if(key>chatCurrentPlace){chatCurrentPlace=key;}
console.log('cCP: '+chatCurrentPlace+' - key: '+key);
and the console logs
cCP: 0 - key: 4
cCP: 4 - key: 4
cCP: 4 - key: 7
cCP: 7 - key: 7
cCP: 7 - key: 8
cCP: 8 - key: 8
cCP: 8 - key: 9
cCP: 9 - key: 9
cCP: 9 - key: 11
cCP: 9 - key: 11
why is the last one not working? it should be cCP: 11 - key: 11
One or both of your variables are probably strings, so are being compared as strings and no numbers. "9" > "11" for the same reason that "b" > "aa" (strings are compared character by character until the first index where they differ).
Convert the values to numbers in your test (e.g. with the Unary + Operator) :
if( +key > +chatCurrentPlace ){ chatCurrentPlace = key; }
or the parseInt function:
if( parseInt(key, 10) > parseInt(chatCurrentPlace, 10) ){ chatCurrentPlace = key; }
You may wish to convert the values before reaching the if so that they remain numbers throughout.
Are you sure the key and cCP values are not taken as strings? It looks like they are sorted alphabetically, unlike numbers. Try
key = parseInt(key,10);
for both of the variables before comparing them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With