如何在Array原型图中获取当前索引?

时间:2021-06-24 22:34:11

I'm using Array.prototype.map.call to store in an array a bunch of node list objects:

我正在使用Array.prototype.map.call将一堆节点列表对象存储在一个数组中:

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
         return {
             rectangle: e.getBoundingClientRect();
         }
    }
}

However, I also want to store the order in which this elements appear in the DOM, and I don't know how to do that.

但是,我还想存储这些元素在DOM中出现的顺序,我不知道该怎么做。

I know that I'm storing this in an array, and the order would be the index of the array. For example:

我知道我将它存储在一个数组中,顺序将是数组的索引。例如:

var listings = getListings();
console.log(listings[0]); // rank #1
console.log(listings[1]); // rank #2
// etc...

but I'm inserting the json object in a database, and the easiest way to store the "rank" information is by creating a property "rank" in my object, but I don't know how to get the "index" of the current array.

但我在数据库中插入json对象,存储“rank”信息的最简单方法是在我的对象中创建属性“rank”,但我不知道如何获取“index”的当前数组。

Something like:

就像是:

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
         return {
             rectangle: e.getBoundingClientRect(),
             rank: magicFunctionThatReturnsCurrentIndex() // <-- magic happens
         }
    }
}

Any help pointing me to the right direction will be greatly appreciated! Thanks

任何指导我正确方向的帮助将不胜感激!谢谢

1 个解决方案

#1


20  

The MDN documentation says:

MDN文档说:

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

使用三个参数调用回调:元素的值,元素的索引和要遍历的Array对象。

So

所以

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e, rank) { // magic 
         return {
             rectangle: e.getBoundingClientRect(),
             rank: rank // <-- magic happens
         }
    }
}

#1


20  

The MDN documentation says:

MDN文档说:

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

使用三个参数调用回调:元素的值,元素的索引和要遍历的Array对象。

So

所以

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e, rank) { // magic 
         return {
             rectangle: e.getBoundingClientRect(),
             rank: rank // <-- magic happens
         }
    }
}