So I'm writing a function to test substrings, and apparently it's telling me that 1 through 3 is greater than 13, this is the code that I'm using:
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);
};
I'm not inexperienced with javascript in any way, but I still can't understand what could be causing this.
Does anyone have any idea where I went wrong? Thanks!
Ah, I figured out the problem just as I finished writing the question, but figured I'd also post it here with the correct answer/why it was happening...
The console.log
was misleading. It was telling me 3 > 13
, which is clearly wrong, but happens to evaluate to true assuming we are talking about "3"
and "13"
as a STRING rather than an integer. That's where I went wrong, comparing wrong data types.
I was plugging in a value from an input[type=number].val()
which I just assumed returned a number, but was wrong. Number inputs return a string when used with .val()
.
var parsedF = parseInt(first)
& var parsedL = parseInt(last)
work as intended.
Hopefully this helps someone!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.