我有以下函数:
(function(){
function closest (num, arr) {
var curr = arr[0];
var diff = Math.abs (num - curr);
for (var val = 0; val < arr.length; val++) {
var newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
}
var _array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362],
_number = 155;
return closest (_number, _array);
})()
结果为162
在这个数组中,我要展示离结果最近的索引!
结果应该是数字4