下划线 forEach 索引?

4
我有一个对象,其中包含以下结构
{
Apples: Array[1],
Mangos: Array[2],
Oranges: Array[5],
Bananas: Array[11]
}

这些值是使用一种工具提取的。
_.forEach(contents, function(values, key) {

}

在这个数组中,key = applesvalues是数组。我想知道如何在此foreach循环中获取当前索引?

比如,我想得到1,2,3,4?除了将它们推入一个数组之外,可能没有其他方法了。


2
"Apples" ≠ "apples"; 1,2,3,4 ≠ 0,1,2,3; - Flavien Volken
2
你应该注意到对象是一个无序的属性集合。 - CD..
1
由于它是一个哈希对象,我认为它不会保留键的顺序。 - Arun P Johny
感谢回复 - 我认为最简单的方法就是将键推入数组并在那里跟踪它,因为无法进行跟踪? - Andy
4
这个对象内部的位置并没有用处或意义。你为什么认为你需要它? - Eevee
2个回答

4

试试这个:

_.each(myArray,function(eachItem,index){
       console.log("item: "+ eachItem + "at index " + index);
    }

例子:

var myArr = [
Apples: "One",
Mangos: "Two",
Oranges: "Three",
Bananas: "Four"
]

_.each(myArr,function(eachItem,index){
       console.log("item: "+ eachItem + "at index " + index);
    }

输出:

第0个索引处的元素: One

第1个索引处的元素: Two

第2个索引处的元素: Three

第3个索引处的元素: Four

参考资料: Underscore JS 参考链接


4

我不确定我完全理解了你的问题,但如果你正在寻找当前枚举项的索引,这里有一种使用"_forEach"等效方法的方式。

var test = {"a":"foo", "b":"bar"}
var index = 0;
for (key in test){ alert(key +"is at "+index+" position"); index++;}

应该是(index++)吧? - Arun P Johny
是的,抱歉 =),正如你所提到的,键没有逻辑顺序约定(只有数组才这样做)。 - Flavien Volken
尽管它不是标准的一部分,但根据这个问题https://dev59.com/AXVC5IYBdhLWcg3weBE-,大多数浏览器似乎共享一个常见的行为。 - Arun P Johny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接