I personally avoid manual iteration whenever possible.
(我个人尽可能避免手动迭代。)
Iterator methods are a concept build upon manual iteration and let objects themself decide how iteration is done.(迭代器方法是基于手动迭代的概念,可以让对象自己决定如何进行迭代。)
So if you have the option, I'd say avoid manual iteration.(因此,如果您有选择,我会避免手动迭代。)
There are a few things to keep in mind.(有几件事要牢记。)
Generally speaking I would avoid iteration methods when altering the collection while iterating.
(一般来说,在迭代时更改集合时,我会避免使用迭代方法。)
Because you don't know the implementation you don't fully know what's happening when adding/removing elements to the collection during iteration.(因为您不知道实现,所以您不完全知道在迭代过程中向集合中添加/删除元素时发生了什么。)
When you explicitly need to work with the index (and not the element) it might be worth the trouble to manually do iteration.
(当您明确需要使用索引(而不是元素)时,手动进行迭代可能会很麻烦。)
With the above being said, it's good to know what iteration methods are available to you, since different methods fulfil different tasks.
(综上所述,最好知道可用的迭代方法,因为不同的方法可以完成不同的任务。)
Knowing which method to use in which scenario will result in better performance and cleaner code.(知道在哪种情况下使用哪种方法将导致更好的性能和更简洁的代码。)
Taking your example I'd change it to the following:
(以您的示例为例,我将其更改为以下内容:)
function getMaxAge(arr, id, max) {
arr = arr.slice();
const matchesId = arr.filter(val => val.id == id),
found = matchId.length;
matchesId.filter(val => val.age < max)
.forEach(val => (val.age = max));
if (!found) arr.push({id: id, age: max});
return arr;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…