Lo-Dash, difference between array and collection

拈花ヽ惹草 提交于 2019-12-03 22:05:58

It's a good idea to look at the more elaborate Underscore.js documentation, from which this distinction is derived. It states:

Collection functions work on arrays, objects, and array-like objects such as arguments, NodeList and similar. But it works by duck-typing, so avoid passing objects with a numeric length property.

Basically, "collections" are things that implement some kind of "iterable" interface, and they internally use the same iteration method (though Lodash source is a bit more convoluted than Underscore). All the "collection methods" do work both on arrays and objects (and a few more iterable things), while the array methods should only be used on arrays (or maybe everything with .length and numeric indices), and the object methods work on any objects.

All Arrays are collections but not all collections are arrays. An Object (i.e. {k: v, ... }) is a collection that is not an Array. Many of the iterators can iterate over non-Array collections just fine. In this context you can think of arrays as, more or less, ordered collections that are indexed by consecutive non-negative integers.

For example, both of these work:

_([6, 11, 23]).each(function() {
    console.log(arguments);
});
_({ a: 6, b: 11, c: 23 }).each(function() {
    console.log(arguments);
});

Demo: http://jsfiddle.net/ambiguous/t8a83/

The arguments that the function gets depend on what sort of thing you're iterating over. If you're iterating over an array then you'd get the element and the index, if you're iterating over an Object then you'd get the value and key.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!