代码之家  ›  专栏  ›  技术社区  ›  steph45

它们是一种在数组中找到最接近0的数字的方法吗?

  •  0
  • steph45  · 技术社区  · 6 年前

    我有一个这样的数组

    var tideArray = new Array(); 
    tideArray.push({tide:"haute1", difference: "-14"});  
    tideArray.push({tide:"haute2", difference: "-3"});  
    tideArray.push({tide:"basse1", difference: "-9"});  
    tideArray.push({tide:"basse2", difference: "4"}); 
    
    tideArray.sortOn("difference", Array.NUMERIC); 
    trace(tideArray[0].tide);
    

    现在,它选择的是最小的数字(-14),但我想选择最接近0的数字。

    有没有办法做到这一点?

    编辑

    我试过了:

    trace(closestToZero(tideArray)); 
    
    
    function closestToZero(a:Array):int  
    {  
        var curDelta:int = Math.abs(0 - a[0].difference);  
        var curIndex:int = 0;  
    
        for(var i:int = 1; i < a.length; i++){  
            var thisDelta:int = Math.abs(0 - a[i].difference);  
            if(thisDelta < curDelta){  
                curIndex = i;  
            }  
        }  
    
        return curIndex;  
    }  
    

    但似乎某个地方有个错误,因为跟踪结果是错误的 3 (这意味着它在告诉我” basse2 " ( 4 )最接近0。。。但是,正如你所看到的,它是“ haute2 " ( -3 )最接近的)。

    2 回复  |  直到 6 年前
        1
  •  1
  •   splash    6 年前

    我认为简单地在数组上循环以找到具有(绝对)最小值的项会更有效 difference 值:

    if (tideArray.length > 0)
    {
        var minItem: Object = tideArray[0];
        for (var index:int = 1; index < tideArray.length; index++)
        {
            if (Math.abs(tideArray[index].difference) < Math.abs(minItem.difference))
            {
                minItem = tideArray[index];
            }
        }
        trace(minItem.tide);
    }
    
        2
  •  1
  •   DatGeoudon    6 年前

    像这样的

    var tideArray = new Array(); 
    ...
    function sortMyArray(a,b):int {
        if (Math.abs(a) < Math.abs(b)) {
            return -1;
        }
        if (Math.abs(a) > Math.abs(b)) {
            return 1;
        }
        return 0;
    }
    tideArray.sort(sortMyArray);
    

    编辑:

    用于您的阵列。

    function sortMyArray(a,b):int {
    
        if (Math.abs(a.difference) < Math.abs(b.difference)) {
            return -1;
        }
        if (Math.abs(a.difference) > Math.abs(b.difference)) {
            return 1;
        }
        return 0;
    }