簡體   English   中英

比較數字時的奇怪行為

[英]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沒有任何經驗,但是我仍然不明白是什么原因引起的。

有人知道我哪里出問題了嗎? 謝謝!

啊,我在寫完問題的時候就發現了問題,但我想也要在這里發布正確的答案/原因。

console.log具有誤導性。 這是在告訴我3 > 13 ,這顯然是錯誤的,但是假設我們將"3""13"視為STRING而不是整數,則碰巧計算為true。 這就是我出錯的地方,比較了錯誤的數據類型。

我從一個input[type=number].val()插入了一個值,我剛剛input[type=number].val()它返回了一個數字,但是是錯誤的。 .val()一起使用時,數字輸入返回一個字符串。

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

希望這可以幫助某人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM