每
_.each
函数接受一个数组或一个对象,一个 iteratee 函数和一个可选的 context
对象,iteratee 函数被调用一次并且为每个数组项调用 iteratee 函数提供 3 个参数
item - The current iterated object (or value if an object was passed)
i - The index of the iterated object (or key if an object was passed)
list - A reference to the original array/list (the object that was passed)
例 1:
_.each(["hello", "underscore"], function(item, i, list) {
alert(item)
});
上面的例子将显示 2 个警报,第一个显示 hello
,第二个显示 world
。
例 2:
_.each({one: 1, two: 2, three: 3}, (value, key, object) =>
console.log(JSON.stringify(object));
);
此示例将记录对象的字符串化版本 3 次。
.each
是一个终端操作,与其他中间函数(map,pluck,values 等)不同,你不需要在 iteratee 函数体内返回。