简体   繁体   English

如何在数组中找到对象的索引号

[英]how do I find an object's index number in an array

I've got this code that is looking for the closest number to 0 in my array : 我有这段代码正在寻找我的数组中最接近0的数字:

var tideArray = new Array();  
tideArray.push({tide:"haute", difference: "-14"});  
tideArray.push({tide:"haute", difference: "3"});  
tideArray.push({tide:"basse", difference: "-4"});  
tideArray.push({tide:"basse", difference: "8"});  

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.difference) // OUTPUT is 3 in this case 

s there a way to find the index of minItem.difference in my tideArray ? 那儿办法找到的指数minItem.differencetideArray (so, the result here should be index = 1 ) (因此,这里的结果应该是index = 1)

I've tried tideArray.indexOf(minItem.difference) but the output is -1 , so the index wasn't found... 我已经尝试过tideArray.indexOf(minItem.difference)但输出为-1 ,所以找不到索引...

I'm looking for the index number and not the value of "difference" or "tide". 我在寻找索引号,而不是“差”或“潮”的值。

尝试使用地图,例如:

tideArray.map(function (cv) { return cv.difference }).indexOf("-14")

A really simple approach would be to record the index using your existing loop: 一个非常简单的方法是使用您现有的循环记录索引:

if (tideArray.length > 0)  
{  
    var mindex: int = NaN;
    var minItem: Object = tideArray[0];  
    for (var index:int = 0; index < tideArray.length; index++)  
    {  
        if (Math.abs(tideArray[index].difference) < Math.abs(minItem.difference))  
        {  
            minItem = tideArray[index];  
            mindex = index;
        }  
    }
    trace("Min item index: " + mindex);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 flash as3 - 如何在数组中找到对象的索引 - flash as3 - how do I find an object's index in an array 如何在 javascript 中找到数组中最小数字的索引 - How do I find the Index of the smallest number in an array in javascript 如何在数组中找到最小的数字并返回该数组的主索引? - How to find lowest number in an array and return that array's primary index? 如何根据索引对象内的值获取特定的数组索引? 柔性 - how do i get the specific array index based on value inside the index's object? flex 如何获取此数组中对象的索引? - How do I get the index of an object in this array? 如何在数组中获取Object索引 - How do i get Object index in an array 如何在Java中找到数组中字符串的索引号 - How do you find the index number of a string in an array in Java 如何根据另一个数组的索引在一个数组中找到一个数组? - How do I find an array in an array based on index of another array? 如何找到关联数组的父数组索引? - How do I find the parent array index for an associative array? 如果我有多个最小数字并且想要两个索引,如何在python数组中找到最小数字的索引? - How do I find the Index of the smallest number in an array in python if I have multiple smallest numbers and want both indexes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM