Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript thinks 8 is larger than 12

Tags:

javascript

function function1() {
  arr = document.getElementById("textfield").value;
  arr = arr.split(",");
  length = arr.length;
  largestNum = -9999;
  for (i = 0; i < length; i++) {
    if (arr[i] > largestNum) {
      largestNum = arr[i];
    }
  }
  alert("Largest number: " + largestNum);
}

can someone tell me what the hell is going on here, i have no idea why it's giving me 8 instead of 12

http://jsfiddle.net/qkLpA/15/

edit - fixed here: http://jsfiddle.net/qkLpA/12/

like image 414
y0ruba Avatar asked Aug 29 '26 16:08

y0ruba


2 Answers

You're splitting a string, so each element of the resulting array will be a string. When you compare strings, it goes character-by-character, and 8 is larger than 1, so it never goes on to the 2.

The solution is to convert the items into numbers after splitting it:

arr = arr.split(",").map(function(s) { return parseInt(s, 10); });

If the map is confusing, you could also be less fancy and just use a for loop to convert them:

arr = arr.split(",");
for(var i = 0; i < arr.length; i++) {
    arr[i] = parseInt(arr[i], 10);
}

You may also want to consider using -Infinity as the initial largestNum rather than -9999.

like image 80
icktoofay Avatar answered Sep 01 '26 07:09

icktoofay


There's a much shorter way to get the largest humber:

function function1() {
  var arr = document.getElementById("textfield").value;
  arr = arr.split(",");
  var max = Math.max.apply(null, arr);
  alert("Largest number: " + max);
}

Fiddle

like image 23
Andy Avatar answered Sep 01 '26 07:09

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!