从数组中查找最小值

Finding minimum value from array

我在尝试查找距数组的最小距离时遇到了一些问题。我得到了从 Servlet 检索到的距离列表,然后遍历它以找到最小值。这是代码:

function getAllTaxiLoc(){
var taxiIcon = [];  
var minDist = 0;
var minDistPlate = "";
$.ajax({
    url: "/TrackNYP/TrackNYPServlet?action=GetAllTaxiLoc",
    type: "GET",
    data: "",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $.each(data, function (i, jsondata) {
            var taxiPlate = jsondata.taxiPlate;
            var taxiLocX = jsondata.taxiLocX;
            var taxiLocY = jsondata.taxiLocY;

            // Calculating to determine if the taxi location is within buffer radius
            var xs = 0;
            var ys = 0;
            xs = taxiLocX - 29770.742075;
            xs = xs * xs; 
            ys = taxiLocY - 40062.99945;
            ys = ys * ys;
            var distance = Math.sqrt( xs + ys );

            if(distance < 800){
            //Plot marker onto map
                if(minDist > distance){
                    minDist = distance;
                    minDistPlate = taxiPlate;
                }
            }

            console.log(minDist + "DIST");
            console.log(minDistPlate + "PLATE");
        });
    },
    error: function (request, state, errors) {
    }
});
}

根据这些代码,我打印出的 minDist 和 minDistPlate 为 0 且为空。有任何想法吗?提前致谢。

您已在代码开头设置 minDist = 0。如果您将它与实际距离进行比较,则 0 始终是最小距离。换句话说,if(minDist > distance) 永远不会 return 为真。您需要设置 minDist = 999999 或比您预期的最小距离大一些的数字。