Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript var=key not working?

Tags:

javascript

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

like image 754
dt192 Avatar asked Sep 05 '26 00:09

dt192


2 Answers

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.

like image 175
Quentin Avatar answered Sep 07 '26 15:09

Quentin


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.

like image 26
tarsis Avatar answered Sep 07 '26 15:09

tarsis