任何人都知道发生了什么事我已经得到了代码
console.log('cCP: '+chatCurrentPlace+' - key: '+key);
if(key>chatCurrentPlace){chatCurrentPlace=key;}
console.log('cCP: '+chatCurrentPlace+' - key: '+key);
Run Code Online (Sandbox Code Playgroud)
和控制台日志
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
Run Code Online (Sandbox Code Playgroud)
为什么最后一个不起作用?它应该是cCP:11 - key:11
您的一个或两个变量可能是字符串,因此被比较为字符串而不是数字."9" > "11"出于同样的原因"b" > "aa"(字符串逐字符比较,直到它们不同的第一个索引).
将值转换为测试中的数字(例如,使用一元+运算符):
if( +key > +chatCurrentPlace ){ chatCurrentPlace = key; }
Run Code Online (Sandbox Code Playgroud)
if( parseInt(key, 10) > parseInt(chatCurrentPlace, 10) ){ chatCurrentPlace = key; }
Run Code Online (Sandbox Code Playgroud)
您可能希望在到达之前转换值,if以便它们始终保持数字.