Chaining

chaining

调用链将导致所有将来的方法调用返回被包装的对象。完成计算后,调用值来检索最终值。下面是将地图/拼合/缩小链接在一起的示例,以便获取歌曲中每个单词的词数。

var lyrics = [ {line: 1, words: "I'm a lumberjack and I'm okay"}, {line: 2, words: "I sleep all night and I work all day"}, {line: 3, words: "He's a lumberjack and he's okay"}, {line: 4, words: "He sleeps all night and he works all day"} ]; _.chain(lyrics) .map(function(line) { return line.words.split(' ' }) .flatten() .reduce(function(counts, word) { counts[word] = (counts[word] || 0) + 1; return counts; }, {}) .value( => {lumberjack: 2, all: 4, night: 2 ... }

此外,Array 原型的方法通过链接的 Underscore 对象进行代理,因此您可以将反向或推入链中,并继续修改数组。

chain

_.chain(obj)

返回一个包装对象。调用此对象的方法将继续返回包装的对象,直到调用值。

var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}]; var youngest = _.chain(stooges) .sortBy(function(stooge){ return stooge.age; }) .map(function(stooge){ return stooge.name + ' is ' + stooge.age; }) .first() .value( => "moe is 21"

value

_.chain(obj).value()

提取包装对象的值。

_.chain([1, 2, 3]).reverse().value( => [3, 2, 1]