从字符串中找到最接近0的数字

Find closest to 0 number from string?

本文关键字:数字 最接近 字符串      更新时间:2023-09-26

我想从由' '分隔的数字组成的字符串输入中得到最接近0的数字。我以以下方式对其进行了编码,它在第一行temps变量上工作,但在第二行temps变量中没有正确运行。这里缺少了什么?

<script type="text/javascript">
//var temps = "9 -2 -8 4 5"; // get 2 & correct
var temps = "-12 -5 -137";   // get -12 & not correct ,expected 5
var temp = temps.split(" ");
var closest = parseInt(temp[0]);
for(var i = 0;i < temp.length ;i++){
    var t = Math.abs(temp[i]);   
    console.log(typeof closest) ; //number : same type
    if(closest > t) {
        closest = t;
    }
}
console.log(closest);
</script>

将-12存储在

最近的变量

当比较你正在做这个

-12>5

为假所以你的赋值是

closest =t;

没有被执行。它对第一个输入有效,因为9被存储为最近的变量。在这一步中,你可以做的是将绝对值存储为最接近的变量。

var closest = parseInt(Math.abs(temp[0]));

修改行

var closest = parseInt(temp[0]);

var closest = Math.abs(parseInt(temp[0]));

你刚刚错过了对第一个索引取绝对值

你可以有一个自定义排序函数,然后选择一个值

function getClosestToZero(str) {
  return str.split(" ").sort(function(a, b) {
    var a1 = Math.abs(a);
    var b1 = Math.abs(b);
    return a1 > b1 ? 1 : a1 < b1 ? -1 : 0
  })[0];
}
var temps = "-12 -5 -137 0 2";
console.log(getClosestToZero(temps))
temps = "11 2 4 5 9 10";
console.log(getClosestToZero(temps))
temps = "-11 -2 -9 3 23";
console.log(getClosestToZero(temps))