简体   繁体   中英

not getting the closest to 0 result

I am not able to find the closest number to 0 its providing me the wrong result.. can you tell me how to fix it... instead of index how to get the value as result -0.001.. providing fiddle and code below

http://jsfiddle.net/YYg8U/7/

var myNumbersToSort = [-1, 2, -3, 4, 0.3,1,-0.001];
function getClosestToZero(set) {
  if(0 === set.length) return null;
  var closest = Math.abs(set[0]), result = 0;
  for(var i in set) {
     var next = Math.abs(set[i]);
     if(closest > next) {
       result = i;
       closest = next;
     }
  }
  return result;  
}

document.getElementById('output').innerHTML = (getClosestToZero(myNumbersToSort));

Good news!

It works. the only thing you missed that your function returns the index Since -0.001 is the closest to 0 it gives six, (array starts from index 0)

I simply tried it with closest as the return value and it worked, try it with different numbers and you will see.

with var myNumbersToSort = [-1, 2,0.000001, -3, 4, 0.3,1,-0.001]

it gives 2 since the second element is 0.000001

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM