javascript - 如何获取数组原型(prototype)图中的当前索引?

标签 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 对象,存储“等级”信息的最简单方法是在我的对象中创建一个属性“等级”,但我不知道如何获取“索引” "当前数组。

类似于:

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

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

最佳答案

MDN documentation说:

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

所以

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

关于javascript - 如何获取数组原型(prototype)图中的当前索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20003676/

相关文章:

html - 如何从 html 中删除#shadow-root(用户代理)

javascript - 在不同的表单中使用输入文件元素

javascript - 有没有办法在所有 jquery 脚本运行后查看网页的源代码?

javascript - 单选按钮上的 Bootstrap-3 Meteor 事件

javascript - 给定一个 JSON 对象,如何根据键查找项目?

javascript - 如何为助手设置默认(全局)选项?

c# - 结构和数组

ios - 从数组中删除项目(带有来自 API 的 JSON 的 Restkit 项目)

javascript - 如何使用 Aurelia.io 增强服务器端生成的页面?

ios - 将 NSManagedObjects 与 JSON 数组的内容进行比较