如何获取数组原型图中的当前索引? [英] How to get current index in Array prototype map?
问题描述
我正在使用 Array.prototype.map.call 将一堆节点列表对象存储在一个数组中:
I'm using Array.prototype.map.call to store in an array a bunch of node list objects:
function getListings() {
return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
return {
rectangle: e.getBoundingClientRect();
}
}
}
但是,我也想存储这个元素在DOM中出现的顺序,不知道怎么做.
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.
我知道我将它存储在一个数组中,顺序将是数组的索引.例如:
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...
但是我在数据库中插入了 json 对象,存储rank"信息的最简单方法是在我的对象中创建一个属性rank",但我不知道如何获取index""的当前数组.
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.
类似于:
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
推荐答案
MDN 文档 说:
callback 使用三个参数调用:元素的值,元素的索引,以及被遍历的 Array 对象.
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
}
}
}
这篇关于如何获取数组原型图中的当前索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!