如何像使用forEach一样循环遍历Immutable List?

18

我想要循环遍历Immutable中的List,我使用了List.map来实现这个目的,虽然可以工作,但不是很好。有没有更好的方法?因为我只是检查数组中的每个元素,如果该元素符合我的规则,我就会执行一些操作,就像Array.forEach一样,我不想像Array.map那样返回任何东西。

例如,这是我目前的工作:

let currentTheme = '';
let selectLayout = 'Layout1';
let layouts = List([{
  name: 'Layout1',
  currentTheme: 'theme1'
},{
  name: 'Layout2',
  currentTheme: 'theme2'
}])


layouts.map((layout) => {
  if(layout.get('name') === selectLayout){
     currentTheme = layout.get('currentTheme');
  }
});
1个回答

16

List.forEach方法适用于Immutable.js列表。

然而,更加函数式的方法是使用List.find方法,示例如下:

let selectLayoutName = 'Layout1';
let layouts = List([Map({
  name: 'Layout1',
  currentTheme: 'theme1'
}),Map({
  name: 'Layout2',
  currentTheme: 'theme2'
})])


selectLayout = layouts.find(layout => layout.get('name') === selectLayoutName);
currentTheme = selectLayout.get('currentTheme')

那么您的代码就没有副作用。


谢谢!List.find类似于Array.filter,这正是我所需要的 :) - Seven Lee
2
不同之处在于 List.find 返回第一个匹配项,而 Array.filter 则提供了满足条件的所有元素列表。 - Mateus Zitelli
1
@SevenLee List.find 就像 Array.find,而 List.filter 就像 Array.filter。记住这点很重要。 - Mihail

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