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.
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:
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:
var arr = ["Hi", "How" "Are", "You"];
var indexes = [];
for(var i = 0; i < arr.length; i++)
indexes.push(i);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.