最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get index within `forEach` iterations in Immutable - Stack Overflow

programmeradmin3浏览0评论

Within native javascript Array.forEach callback function, we have arguments as: currentValue[, index[, array]].

In Immutable.js forEach, I cannot seem to get the index value. I think it used to follow the pattern of Array.forEach, however, they have changed it.

My question is: how does one get index within each iteration of forEach. Are we to manually increment an external (outside the function) varible to store a value?

example code:

const anObj = Map({
 a : "a",
 b : "b"
});
let i;
// immutable.js way
anObj.forEach((v, k, collection ) => {
 // body of func
}

Within native javascript Array.forEach callback function, we have arguments as: currentValue[, index[, array]].

In Immutable.js forEach, I cannot seem to get the index value. I think it used to follow the pattern of Array.forEach, however, they have changed it.

My question is: how does one get index within each iteration of forEach. Are we to manually increment an external (outside the function) varible to store a value?

example code:

const anObj = Map({
 a : "a",
 b : "b"
});
let i;
// immutable.js way
anObj.forEach((v, k, collection ) => {
 // body of func
}
Share Improve this question asked Aug 2, 2018 at 14:45 KayoteKayote 15.7k26 gold badges96 silver badges152 bronze badges 2
  • Why not use a for loop? for(let i = 0; i < anObj.length; i++){...}. Also, Map is an existing class in HTML5, are you sure you want to keep using something that overwrites native methods? – BRO_THOM Commented Aug 2, 2018 at 14:56
  • @BRO_THOM This is an immutable Map obj. – Kayote Commented Aug 2, 2018 at 15:07
Add a ment  | 

2 Answers 2

Reset to default 2

var index = anObj.indexOf(v);

Should return you the index of your value given value. Might be inefficient, pared to an incremental variable.

https://github./facebook/immutable-js/issues/586

Unfortunately, it appears that the dev team decided to deviate from the native Javascript signature as per the above link. So, in essense the remended approach, as per LeeByron's ment is:

var index = 0;
myOrderedMap.forEach(function (item) {
  // do what you need to do with item and index
  index += 1;
});
发布评论

评论列表(0)

  1. 暂无评论