javascript - 数数错误

标签 javascript node.js if-statement numbers

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

我在服务器上保存了一个“当前正在运行”的剪辑,然后发送下一个或上一个剪辑的 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 的数字会被错误地评估,即使控制台显示它们是按预期接收的。

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

控制台(始终单击快进按钮):

'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()返回一个字符串,字符串的比较是通过逐个字符进行比较来完成的,因此:

  • “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

关于javascript - 数数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29771728/

相关文章:

javascript - 构建介绍,阅读App本地设置

javascript - 在 Jquery.load 调用 JavaScript 函数

javascript - 使用 javascript 检索 IFrame 内容

node.js - 错误:Redis与127.0.0.1:6379的连接失败-连接ECONNREFUSED 127.0.0.1:6379 Heroku

python - if 语句如何工作?

javascript - jquery搜索结果过滤

python - Tchannel 服务器代码不工作。 (Python 和 Node.js)

javascript - 从 Node 产生时ffmpeg缓冲标准输入

r - 应用 if else 条件在 r 中创建新列

java - 当前时间 IF 语句 GT ThrustLag