我正在处理一些使用许多不同项目“列表”的 NodeJS 代码。底层实现使用包括 Immutable.List、Immutable.Set、Javascript Array 和 Javascript Set。
出于我不会讨论的原因,我希望能够在不考虑基础集合的情况下循环遍历这些项目。
一些背景知识可能会有用。对于数组,我可以使用以下代码循环遍历 Javascript 数组。
let anArray = [ new SomeObj(), new SomeObj(), ... ]
for(let idx=0; idx < anArray.length; idx++){
let someObj = anArray[idx];
// ... etc
if (someCondition) break;
}
对于 Immutable.List,我需要使用 Immutable.List.size 属性(而不是 length 属性)并使用“Immutable.List.get”函数,如下所示:
const immutable = require('immutable');
let aList = immutable.List([ new SomeObj(), new SomeObj(), ... ]);
for(idx=0; idx < aList.size; idx++){
var item = aList.get(idx);
// ... etc
if (someCondition) break;
}
除了一些小差异外,循环逻辑非常接近。
对于那些会建议使用 forEach() 方法的自然答案的人,该方法可用于这些对象中的每一个。普通的 Javascript Array.forEach()方法不处理循环的中断(在这种情况下需要 Array.some() 方法)。 Immutable.List 基于 Immutable.Collection.forEach确实支持“打破”循环,因此这可能有效,但需要将 Javascript 对象包装到不可变序列/集合中。我刚开始使用 Immutable 库,因此熟悉 Immutable 的人可能还知道另一种方法。
接下来将介绍我正在考虑的方法。 我正在考虑提供如下解决方案的效用函数:
for(let idx=0, looper=new Looper(aListOrSet); idx < looper.length(); idx++){
var item = looper.get(idx);
// ... etc
if (someCondition) break;
}
我看过的一些东西包括:
- How to loop through Immutable List like forEach
- Immutable.Collection.forEach
- Immutable Sequences - 这可能就是诀窍。我必须将 Javascript 对象转换为不可变序列,但这可能有效。
有没有其他人试图解决这个问题,如果有,他们是如何解决这个问题的?
最佳答案
你可以使用 for...of
环形。这允许您对任何 Iterable 进行操作对象,包括内置集合和 Immutable.js 集合。
for (let element of collection) {
// do something with element
if (someCondition) {
break;
}
}
它不会像常规 for
循环或 forEach
那样让您访问迭代索引,但这很容易让您自己跟踪:
let i = 0;
for (let element of collection) {
// do something with element
if (someCondition) {
break;
}
i++;
}
您可能还想阅读 How to short circuit Array.forEach like calling break .它列出了一些解决方案,包括 for...of
应该适用于您要使用的所有集合:
- 将循环包装在
try
中并抛出异常以中断 - 使用
.some()
和return true
来中断
关于javascript - 我可以使用相同的代码遍历 immutable.List、immutable.Set 或 Javascript Array 或 Set 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47824494/