【问题标题】:How to nest loops with iterators?如何使用迭代器嵌套循环?
【发布时间】:2018-08-01 06:19:59
【问题描述】:

我有以下代码:

let array = [0,1,2];
for (let i = 0; i < array.length; i++)
    for (let j = i + 1; j < array.length; j++) // j starts at i+1
        console.log(array[i], array[j]);

但由于重复项目,我决定将我的数组转换为地图。现在我想像上面那样在地图上进行迭代:

let map = array.reduce(countIntoMap, new Map());
for (let [i,counti] of map.entries())
    for (let [j,countj] of map.entries()) // j starts at 0
        console.log(array[i], array[j]);

如何从i + 1 开始循环?


编辑:这里是重要的函数,因为我想知道每个元素出现了多少次。

function countIntoMap (map, element) {
    if ( ! map.has(element) )
        map.set(element, 1);
    else
        map.set(element, map.get(element) + 1);
    return map;
}

【问题讨论】:

  • 地图没有可寻址的顺序。
  • 什么是countIntoMap
  • 谢谢@NinaScholz。地图保持插入元素的顺序。我们不能利用它吗?任何替代结构?
  • 请在编辑中添加一个示例,您想要实现什么。顺便说一句,我这里没有发电机。
  • 取一个给定的数组。为什么是地图,为什么是生成器(没有出现)?

标签: javascript iterator


【解决方案1】:

这将创建 {key, count} 对象数组,并且可以根据需要对其进行迭代

let array = [0, 1, 2, 2];

const uniq = array.reduce((acc, a) => {

  let idx = acc.findIndex(b => b.key === a);
  idx === -1 ? acc.push({ key: a, count: 1}) : ++acc[idx].count;
  return acc;

}, []);


for (let i = 0; i < uniq.length; ++i) {
  for (let j = i + 1; j < uniq.length; ++j) {
    console.log(uniq[i].count, uniq[j].count);
  }
}

【讨论】:

  • 谢谢,我相信我应该使用数组而不是地图。我的问题变成了“如何在不转换为数组的情况下循环地图?”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
相关资源
最近更新 更多