【问题标题】:How to get current index in Array prototype map?如何在数组原型图中获取当前索引?
【发布时间】:2013-11-15 14:44:42
【问题描述】:

我正在使用 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
         }
    }
}

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

【问题讨论】:

  • 我认为 document.querySelectorAll('li.g') 应该以正确的顺序返回元素,即它们在 DOM 中的显示方式。
  • 是的,但是有没有办法得到数值?我有当前顺序的元素,但我想在我的 JSON 对象中有一个属性及其数值。

标签: javascript arrays dom prototypejs prototype


【解决方案1】:

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
         }
    }
}

【讨论】:

  • 我一遍又一遍地阅读该页面,无论出于何种原因,我从未注意到索引也被传递。谢谢!
猜你喜欢
  • 2010-11-29
  • 2021-11-12
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 2011-06-28
  • 2022-08-11
  • 2018-08-13
  • 1970-01-01
相关资源
最近更新 更多