比较数字时的奇怪行为

Strange behavior when comparing numbers

所以我正在编写一个函数来测试子字符串,显然它告诉我 1 到 3 大于 13,这是我正在使用的代码:

var highlight = function(first,last,whichsub){
  var text = $(".output2").text();
  if(whichsub === "substring"){
    text = text.substring(0,first)+"<color style='background:#0763D3'>"+text.substring(first,last)+"</color>"+text.substring(last);
  }else if(whichsub === "substr"){
    text = text.substr(0,first)+"<color style='background:#0763D3'>"+text.substr(first,last)+"</color>"+text.substr(last);
  }
  //console.log(text);
  console.log(first+" "+last);
  if(first > last){console.log("true");} // is printing true
  $(".output2").html(text);
};

我对 javascript 一点都不陌生,但我仍然不明白是什么原因造成的。

有人知道我哪里出错了吗?谢谢!

啊,我刚写完问题就发现了问题,但我想我也会post这里用正确的answer/why它正在发生...

console.log 具有误导性。它告诉我 3 > 13,这显然是错误的,但假设我们正在谈论 "3""13" 作为 STRING而不是一个整数。那是我出错的地方,比较了错误的数据类型。

我插入了一个 input[type=number].val() 的值,我只是假设 return 输入了一个数字,但我错了。当与 .val().

一起使用时,数字输入 return 一个字符串

var parsedF = parseInt(first) & var parsedL = parseInt(last) 按预期工作。

希望这对某人有所帮助!