Underscore 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

遍历

_.each(list, iteratee, [context])

遍历list中的所有元素,按顺序用遍历输出每个元素。如果传递了context参数,则把iteratee绑定到context对象上。

每次调用iteratee都会传递三个参数:(element, index, list)。如果list是个JavaScript对象,iteratee的参数是 (value, key, list))。返回list以方便链式调用。

    _.each([1, 2, 3], alert);

    => alerts each number in turn...

    _.each({one: 1, two: 2, three: 3}, alert);

    => alerts each number value in turn...

注意:集合函数能在数组,对象,和类数组对象,比如arguments, NodeList和类似的数据类型上正常工作。

但是它通过鸭子类型工作,所以要避免传递一个不固定length属性的对象。每个循环不能被破坏打破, 使用_.find(后面的章节会讲解到)代替,这也是很好的注意。

_.map(list, iteratee, [context])

通过转换函数(iteratee迭代器)映射列表中的每个值产生价值的新数组。

iteratee传递三个参数:value,然后是迭代 index,最后一个是引用指向整个list。

    _.map([1, 2, 3], function(num){ return num * 3; });

    => [3, 6, 9]

    _.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });

    => [3, 6, 9]

    _.map([[1, 2], [3, 4]], _.first);

    => [1, 3]
将上文中的示例,在右侧javascript代码框中实现, 并利用document.write 进行输出查看结果。如右侧示例: PS:后文中的练习将不会预知代码。