我正在使用 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
}
}
}
任何帮助我指明正确方向的人都将不胜感激!谢谢
最佳答案
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/