简体   繁体   English

如何获取此数组中对象的索引?

[英]How do I get the index of an object in this array?

I have an array of objects as follows: 我有一个对象数组,如下所示:

myArr:[obj{}. obj{}, obj{}, obj{}]

How can I return the index of each object in the array? 如何返回数组中每个对象的索引? This snippet is inside a bigger for loop which will iterate the same amount of times as there are objects in my array. 此代码段位于一个较大的for循环内,该循环将迭代与我的数组中的对象相同的时间。

var ret = 'Index: '

if(myArr.length > 0){
    var idx = myArr.obj.index??

    var ret += idx;
}

console.log(ret); //Which will hopefully be Index: 0 etc...

Any advice would be greatly appreciated. 任何建议将不胜感激。 Cheers 干杯

JavaScript Array provides an indexOf method that returns the index of the passed-in value: JavaScript Array提供了一个indexOf方法,该方法返回传入值的索引:

var o1 = {foo: 'bar'}
var o2 = {foo: 'bar'}

var a = [o1, o2]

console.log(a.indexOf(o1)) // 0
console.log(a.indexOf(o2)) // 1

I can't comment, but the array indexes will be a list of numbers from 0 to myArr.length - 1. To get the list you could do the following: 我无法发表评论,但是数组索引将是从0到myArr.length-1的数字列表。要获取该列表,您可以执行以下操作:

var arr = ["Hi", "How" "Are", "You"];
var indexes = [];

for(var i = 0; i < arr.length; i++)
    indexes.push(i);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM