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

ILi*_*cos 11 javascript arrays dom prototype prototypejs

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

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

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

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

var listings = getListings();
console.log(listings[0]); // rank #1
console.log(listings[1]); // rank #2
// etc...
Run Code Online (Sandbox Code Playgroud)

但我在数据库中插入json对象,存储"排名"信息的最简单方法是在我的对象中创建属性"rank",但我不知道如何获取"索引"当前数组.

就像是:

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

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

Tib*_*bos 22

该MDN文档说:

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

所以

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

  • 我一遍又一遍地阅读那个页面,无论出于什么原因,我都没有注意到索引也被传递了.谢谢! (2认同)