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

时间:2013-11-15 14:44:42

标签: javascript arrays dom prototypejs prototype

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

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

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

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

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

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

类似的东西:

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

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

1 个答案:

答案 0 :(得分:21)

MDN documentation说:

  使用三个参数调用

回调:元素的值,   元素的索引和遍历的Array对象。

所以

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