JavaScript学习笔记-Underscore Collections
It has been 1485 days since the last update, the content of the article may be outdated.
Installation
- Node.js
npm install underscore
- Meteor.js
meteor add underscore
- Require.js
require(["underscore"], ...
- Bower
bower install underscore
- Component
component install jashkenas/underscore
collections 工具
map/filter
和Array的map()与filter()类似,但是underscore的map()和filter()可以作用于Object。
当作用于Object时,传入的函数为function (value, key),第一个参数接收value,第二个参数接收key:
plaintext
var obj = { |
_.mapObject 返回对象。
_.some _.every
当集合的所有元素都满足条件时,_.every()函数返回true,当集合的至少一个元素满足条件时,_.some()函数返回true:
plaintext
'use strict'; |
当集合是Object时,我们可以同时获得value和key:
plaintext
'use strict'; |
max / min
这两个函数直接返回集合中最大和最小的数:
plaintext
var arr = [3, 5, 7, 9]; |
如果集合是Object,max()和min()只作用于value,忽略掉key:
groupBy
groupBy()把集合的元素按照key归类,key由传入的函数返回:
plaintext
var scores = [20, 81, 75, 40, 91, 59, 77, 66, 72, 88, 99]; |
shuffle / sample
shuffle()用洗牌算法随机打乱一个集合;
sample()则是随机选择一个或多个元素。
plaintext
_.shuffle([1, 2, 3, 4, 5, 6]); // [3, 5, 4, 6, 2, 1] 注意每次结果都不一样: |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment