他们是一种在阵列中找到最接近0的数字的方法吗?

时间:2018-01-23 07:23:19

标签: arrays actionscript-3

我有一个像这样的数组

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),但我想选择最接近数字的数字。

有办法吗?

编辑

我试过了:

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(所以这意味着它告诉我&#34; basse2&#34;({ {1}})最接近0 ...但是,正如您所看到的,它是&#34; 4&#34;(haute2)最接近的)。

2 个答案:

答案 0 :(得分:1)

像这样的东西

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;
}

答案 1 :(得分:1)

我认为简单地循环遍历数组以找到具有(绝对)最小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);
}