如何像forEach一样遍历不可变列表? [英] How to loop through Immutable List like forEach?
问题描述
我想遍历Immutable List
,我用List.map
来做到这一点,它可以工作,但效果不好.有没有更好的办法?因为我只检查数组中的每个元素,所以如果该元素符合我的规则,我会做某些事情,就像Array.forEach
一样,我不想返回任何Array.map
这样的东西.
I would like to loop through Immutable List
, I used List.map
to do it, it can be worked, but not good. is there are a better way? Because I just check each element in array, if the element match my rule, I do something, just like Array.forEach
, I don't want to return anything like Array.map
.
例如,这是我现在的工作:
for example, it is my work now:
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');
}
});
推荐答案
Immutable.js列表中存在方法List.forEach
.
The method List.forEach
exists for Immutable.js lists.
但是,一种更实用的方法将使用方法List.find
如下:
However, a more functional approach would be using the method List.find
as follows:
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')
然后您的代码没有副作用.
Then your code doesn't have side-effects.
这篇关于如何像forEach一样遍历不可变列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!