数错了

counting numbers wrong

我遇到了一个奇怪的问题。

我在我的服务器上保存了一个 "current running" 剪辑,然后发送下一个或上一个剪辑的 ID 以确定我是否需要向前或向后跳过。

if ((request.command.substring(15) > device.currentClip)) {
            console.log("XXXXX command: " + request.command.substring(15));
            console.log("XXXXX current clip " + device.currentClip);
            console.log("[INFO] skipping forward (playlist)");
            return;
}  else if ((request.command.substring(15) < device.currentClip)) {
            console.log("XXXXX command: " + request.command.substring(15));
            console.log("XXXXX current clip " + device.currentClip);
            console.log("[INFO] skipping backward (playlist)");
            return;
}

奇怪的是,超过 10 的数字被错误地评估,即使控制台显示它们是按预期接收的。

这是为什么?它可能与错误的类型有关吗?我希望它们是自动输入的,或者至少会抛出一个错误。但他们似乎只是 "wrong".

控制台(总是点击快进按钮):

'goto: clip id: 12'
XXXXX command: 12
XXXXX current clip 11
[INFO] skipping forward (playlist)
'goto: clip id: 10'
XXXXX command: 10
XXXXX current clip 9
[INFO] skipping backward (playlist)

谁能解释一下(可能的)错误?

substring() returns一个字符串,字符串的比较是逐个字符比较的,因此:

  • “10”<“9”,并且
  • “10”<“11”

可以使用parseInt函数将两边都转换成int(如果device.currentClip已经是int就不需要再转换了) :

var intCommand = parseInt(request.command.substring(15), 10);
var intCurrentClip = parseInt(device.currentClip);
if (intCommand > intCurrentClip)) {
// the rest of the code