1. 程式人生 > >underscore知識點

underscore知識點

一、安裝(Installation)

Node.js --> npm install underscore

Meteor.js --> meteor add underscore

Require.js --> require(["underscore"], ...

Bower bower --> install underscore

Component --> component install jashkenas/underscore

二、集合函式 (陣列 或物件)

1、each

語法:_.each(list, iteratee, [context])

說明:遍歷list中的所有元素,按順序用每個元素當做引數呼叫 iteratee 函式。如果傳遞了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...

2、map

語法:_.map(list, iteratee, [context])

說明:通過對list裡的每個元素呼叫轉換函式(iteratee迭代器)生成一個與之相對應的陣列。iteratee傳遞三個引數:value,然後是迭代 index(或 key 愚人碼頭注:如果list是個JavaScript物件是,這個引數就是key),最後一個是引用指向整個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]

3、reduce

語法:_.reduce(list, iteratee, [memo], [context])

說明:別名為 inject 和 foldl, reduce方法把list中元素歸結為一個單獨的數值。Memo是reduce函式的初始值,會被每一次成功呼叫iteratee函式的返回值所取代 。這個迭代傳遞4個引數:memo,value 和 迭代的index(或者 key)和最後一個引用的整個 list。

如果沒有memo傳遞給reduce的初始呼叫,iteratee不會被列表中的第一個元素呼叫。第一個元素將取代memo引數傳遞給列表中下一個元素呼叫的iteratee函式。

例子:

var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);

=> 6

4、reduceRight

語法:_.reduceRight(list, iteratee, memo, [context])

說明:reducRight是從右側開始組合元素的reduce函式, Foldr在 JavaScript 中不像其它有惰性求值的語言那麼有用(愚人碼頭注:lazy evaluation:一種求值策略,只有當表示式的值真正需要時才對表示式進行計算)。

例子:

var list = [[0, 1], [2, 3], [4, 5]];

var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);

=> [4, 5, 2, 3, 0, 1]

// concat() 方法用於連線兩個或多個數組。

5、find

語法:_.find(list, predicate, [context])

說明:在list中逐項查詢,返回第一個通過predicate迭代函式真值檢測的元素值,如果沒有元素通過檢測則返回 undefined。 如果找到匹配的元素,函式將立即返回,不會遍歷整個list。

例子:

var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

=> 2

6、filter

語法:_.filter(list, predicate, [context])

說明:遍歷list中的每個值,返回所有通過predicate真值檢測的元素所組成的陣列。(愚人碼頭注:如果存在原生filter方法,則用原生的filter方法。)

例子:

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

=> [2, 4, 6]

7、where

語法:_.where(list, properties)

說明:遍歷list中的每一個值,返回一個數組,這個數組裡的元素包含 properties 所列出的鍵 - 值對。

例子:

_.where(listOfPlays, {author: "Shakespeare", year: 1611});

=> [{title: "Cymbeline", author: "Shakespeare", year: 1611},

           {title: "The Tempest", author: "Shakespeare", year: 1611}]

8、findWhere

語法:_.findWhere(list, properties)

說明:遍歷整個list,返回匹配 properties引數所列出的所有 鍵 - 值 對的第一個值。

如果沒有找到匹配的屬性,或者list是空的,那麼將返回undefined。

例子:

_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});

=> {year: 1918, newsroom: "The New York Times",

       reason: "For its public service in publishing in full so many official reports, documents and speeches by European statesmen relating to the progress and conduct of the war."}

9、reject

語法:_.reject(list, predicate, [context])

說明:返回list中沒有通過predicate真值檢測的元素集合,與filter相反

例子:

var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

=> [1, 3, 5]

10、every

語法:_.every(list, [predicate], [context])

說明:如果list中的所有元素都通過predicate的真值檢測就返回true。(愚人碼頭注:如果存在原生的every方法,就使用原生的every。)

例子:

_.every([true, 1, null, 'yes'], _.identity);

=> false

11、some

語法:_.some(list, [predicate], [context])

說明:如果list中有任何一個元素通過 predicate 的真值檢測就返回true。一旦找到了符合條件的元素, 就直接中斷對list的遍歷. (愚人碼頭注:如果存在原生的some方法,就使用原生的some。)

例子:

_.some([null, 0, 'yes', false]);

=> true

12、contains

語法:_.contains(list, value, [fromIndex])

說明:如果list包含指定的value則返回true(愚人碼頭注:使用===檢測)。如果list 是陣列,內部使用indexOf判斷。使用fromIndex來給定開始檢索的索引位置。

例子:

_.contains([1, 2, 3], 3);

=> true

13、invoke

語法:_.invoke(list, methodName, *arguments)

說明:在list的每個元素上執行methodName方法。 任何傳遞給invoke的額外引數,invoke都會在呼叫methodName方法的時候傳遞給它。

例子:

_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');

=> [[1, 5, 7], [1, 2, 3]]

14、pluck

語法:_.pluck(list, propertyName)

說明:pluck也許是map最常使用的用例模型的簡化版本,即萃取陣列物件中某屬性值,返回一個數組。

例子:

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

_.pluck(stooges, 'name');

=> ["moe", "larry", "curly"]

15、max

語法:_.max(list, [iteratee], [context])

說明:返回list中的最大值。如果傳遞iteratee引數,iteratee將作為list中每個值的排序依據。如果list為空,將返回-Infinity,所以你可能需要事先用isEmpty檢查 list 。

例子:

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

_.max(stooges, function(stooge){ return stooge.age; });

=> {name: 'curly', age: 60};

16、min

語法:_.min(list, [iteratee], [context])

說明:返回list中的最小值。如果傳遞iteratee引數,iteratee將作為list中每個值的排序依據。如果list為空,將返回Infinity,所以你可能需要事先用isEmpty檢查 list 。

例子:

var numbers = [10, 5, 100, 2, 1000];

_.min(numbers);

=> 2

17、sortBy

語法:_.sortBy(list, iteratee, [context])

說明:返回一個排序後的list拷貝副本。如果傳遞iteratee引數,iteratee將作為list中每個值的排序依據。用來進行排序迭代器也可以是屬性名稱的字串(比如 length)。

例子:

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });

=> [5, 4, 6, 3, 1, 2]

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

_.sortBy(stooges, 'name');

=> [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];

18、groupBy

語法:_.groupBy(list, iteratee, [context])

說明:把一個集合分組為多個集合,通過 iterator 返回的結果進行分組. 如果 iterator 是一個字串而不是函式, 那麼將使用 iterator 作為各元素的屬性名來對比進行分組.

例子:

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });

=> {1: [1.3], 2: [2.1, 2.4]}

_.groupBy(['one', 'two', 'three'], 'length');

=> {3: ["one", "two"], 5: ["three"]}

19、indexBy

語法:_.indexBy(list, iteratee, [context])

說明:給定一個list,和 一個用來返回一個在列表中的每個元素鍵 的iterator 函式(或屬性名), 返回一個每一項索引的物件。和groupBy非常像,但是當你知道你的鍵是唯一的時候可以使用indexBy 。

例子:

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

_.indexBy(stooges, 'age');

=> {

  "40": {name: 'moe', age: 40},

  "50": {name: 'larry', age: 50},

  "60": {name: 'curly', age: 60}

}

20、countBy

語法:_.countBy(list, iteratee, [context])

說明:排排序一個列表組成多個組,並且返回各組中的物件的數量的計數。類似groupBy,但是不是返回列表的值,而是返回在該組中值的數目。

例子:

_.countBy([1, 2, 3, 4, 5], function(num) {

  return num % 2 == 0 ? 'even': 'odd';

});

=> {odd: 3, even: 2}

21、shuffle

語法:_.shuffle(list)

說明:返回一個隨機亂序的 list 副本, 使用 Fisher-Yates shuffle 來進行隨機亂序.

例子:

_.shuffle([1, 2, 3, 4, 5, 6]);

=> [4, 1, 6, 3, 5, 2]

22、sample

語法:_.sample(list, [n])

說明:從 list中產生一個隨機樣本。傳遞一個數字表示從list中返回n個隨機元素。否則將返回一個單一的隨機項。

例子:

_.sample([1, 2, 3, 4, 5, 6]);

=> 4

_.sample([1, 2, 3, 4, 5, 6], 3);

=> [1, 6, 2]

23、toArray

語法:_.toArray(list)

說明:把list(任何可以迭代的物件)轉換成一個數組,在轉換 arguments 物件時非常有用。

例子:

(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);

=> [2, 3, 4]

24、size

語法:_.size(list)

說明:返回list的長度。

例子:

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

=> 3

25、partition

語法:_.partition(array, predicate)

說明:拆分一個數組(array)為兩個陣列:  第一個陣列其元素都滿足predicate迭代函式, 而第二個的所有元素均不能滿足predicate迭代函式。

例子:

_.partition([0, 1, 2, 3, 4, 5], isOdd);

=> [[1, 3, 5], [0, 2, 4]]

三、陣列函式(Array Functions)

注: 所有的陣列函式也可以用於 arguments (引數)物件。 但是,Underscore函式不能用於稀疏("sparse" ) 陣列。

1、first

語法:_.first(array, [n])

說明:返回array (陣列)的第一個元素。傳遞 n引數將返回陣列中從第一個元素開始的n個元素(愚人碼頭注:返回陣列中前 n 個元素.)。

例子:

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

=> 5

2、initial

語法:_.initial(array, [n])

說明:返回陣列中除了最後一個元素外的其他全部元素。 在arguments物件上特別有用。傳遞 n引數將從結果中排除從最後一個開始的n個元素(愚人碼頭注:排除陣列後面的 n 個元素)。

例子:

_.initial([5, 4, 3, 2, 1]);

=> [5, 4, 3, 2]

3、last

語法:_.last(array, [n])

說明:返回array(陣列)中最後一個元素。傳遞 n引數將返回陣列中從最後一個元素開始的n個元素(愚人碼頭注:返回數組裡的後面的n個元素)。

例子:

_.last([5, 4, 3, 2, 1]);

=> 1

4、rest

語法:_.rest(array, [index])

說明:返回陣列中除了第一個元素外的其他全部元素。傳遞 index 引數將返回從index開始的剩餘所有元素 。

例子:

_.rest([5, 4, 3, 2, 1]);

=> [4, 3, 2, 1]

5、compact

語法:_.compact(array)

說明:返回一個除去了所有false值的 array副本。 在javascript中, false, null, 0, "", undefined 和 NaN 都是false值.

例子:

_.compact([0, 1, false, 2, '', 3]);

=> [1, 2, 3]

6、flatten

語法:_.flatten(array, [shallow])

說明:將一個巢狀多層的陣列 array(陣列) (巢狀可以是任何層數)轉換為只有一層的陣列。 如果你傳遞 shallow引數,陣列將只減少一維的巢狀。

例子:

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

=> [1, 2, 3, 4];

_.flatten([1, [2], [3, [[4]]]], true);

=> [1, 2, 3, [[4]]];

7、without

語法:_.without(array, *values)

說明:返回一個刪除所有values值後的 array副本。(愚人碼頭注:使用===表示式做相等測試。)

例子:

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);

=> [2, 3, 4]

8、union

語法:_.union(*arrays)

說明:返回傳入的 arrays(陣列)並集:按順序返回,返回陣列的元素是唯一的,可以傳入一個或多個 arrays (陣列)。

例子:

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);

=> [1, 2, 3, 101, 10]

9、intersection

語法:_.intersection(*arrays)

說明:返回傳入 arrays(陣列)交集。結果中的每個值是存在於傳入的每個arrays(陣列)裡。

例子:

_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);

=> [1, 2]

10、difference

語法:_.difference(array, *others)

說明:類似於without,但返回的值來自array引數陣列,並且不存在於other 陣列。

例子:

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);

=> [1, 3, 4]

11、uniq

語法:_.uniq(array, [isSorted], [iteratee])

說明:返回 array去重後的副本, 使用 === 做相等測試. 如果您確定 array 已經排序, 那麼給 isSorted 引數傳遞 true值, 此函式將執行的更快的演算法. 如果要處理物件元素, 傳遞 iteratee函式來獲取要對比的屬性.

例子:

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

=> [1, 2, 3, 4]

12、zip

語法:_.zip(*arrays)

說明:將 每個arrays中相應位置的值合併在一起。在合併分開儲存的資料時很有用. 如果你用來處理矩陣巢狀陣列時, _.zip.apply 可以做類似的效果。

例子:

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);

=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

13、unzip

語法:_.unzip(*arrays)

說明:與zip功能相反的函式,給定若干arrays,返回一串聯的新陣列,其第一元素個包含所有的輸入陣列的第一元素,其第二包含了所有的第二元素,依此類推。通過apply用於傳遞陣列的陣列。

例子:

_.unzip([['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]])

=> ["moe", 30, true], ["larry", 40, false], ["curly", 50, false]

14、object

語法:_.object(list, [values])

說明:將陣列轉換為物件。傳遞任何一個單獨[key, value]對的列表,或者一個鍵的列表和一個值得列表。 如果存在重複鍵,最後一個值將被返回。

例子:

_.object(['moe', 'larry', 'curly'], [30, 40, 50]);

=> {moe: 30, larry: 40, curly: 50}

_.object([['moe', 30], ['larry', 40], ['curly', 50]]);

=> {moe: 30, larry: 40, curly: 50}

15、indexOf

語法:_.indexOf(array, value, [isSorted])

說明:返回value在該 array 中的索引值,如果value不存在 array中就返回-1。使用原生的indexOf 函式,除非它失效。如果您正在使用一個大陣列,你知道陣列已經排序,傳遞true給isSorted將更快的用二進位制搜尋..,或者,傳遞一個數字作為第三個引數,為了在給定的索引的陣列中尋找第一個匹配值。

例子:

_.indexOf([1, 2, 3], 2);

=> 1

16、lastIndexOf

語法:_.lastIndexOf(array, value, [fromIndex])

說明:返回value在該 array 中的從最後開始的索引值,如果value不存在 array中就返回-1。如果支援原生的lastIndexOf,將使用原生的lastIndexOf函式。傳遞fromIndex將從你給定的索性值開始搜尋。

例子:

_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);

=> 4

17、sortedIndex

語法:_.sortedIndex(list, value, [iteratee], [context])

說明:使用二分查詢確定value在list中的位置序號,value按此序號插入能保持list原有的排序。如果提供iterator函式,iterator將作為list排序的依據,包括你傳遞的value 。iterator也可以是字串的屬性名用來排序(比如length)。

例子:

_.sortedIndex([10, 20, 30, 40, 50], 35);

=> 3

var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}];

_.sortedIndex(stooges, {name: 'larry', age: 50}, 'age');

=> 1

18、findIndex

語法:_.findIndex(array, predicate, [context])

說明:類似於_.indexOf,當predicate通過真檢查時,返回第一個索引值;否則返回-1。

例子:

_.findIndex([4, 6, 8, 12], isPrime);

=> -1 // not found

_.findIndex([4, 6, 7, 12], isPrime);

=> 2

19、findLastIndex

語法:_.findLastIndex(array, predicate, [context])

說明:和_.findIndex類似,但反向迭代陣列,當predicate通過真檢查時,最接近末端的索引值將被返回。

例子:

var users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},

             {'id': 2, 'name': 'Ted', 'last': 'White'},

             {'id': 3, 'name': 'Frank', 'last': 'James'},

             {'id': 4, 'name': 'Ted', 'last': 'Jones'}];

_.findLastIndex(users, {

  name: 'Ted'

});

=> 3

20、range

語法:_.range([start], stop, [step])

說明:一個用來建立整數靈活編號的列表的函式,便於each 和 map迴圈。如果省略start則預設為 0;step 預設為 1.返回一個從start 到stop的整數的列表,用step來增加 (或減少)獨佔。值得注意的是,如果stop值在start前面(也就是stop值小於start值),那麼值域會被認為是零長度,而不是負增長。-如果你要一個負數的值域 ,請使用負數step.

例子:

_.range(10);

=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

_.range(1, 11);

=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

_.range(0, 30, 5);

=> [0, 5, 10, 15, 20, 25]

_.range(0, -10, -1);

=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

_.range(0);

=> []

四、與函式有關的函式(Function(uh, ahem) Function)

1、bind

語法:_.bind(function, object, *arguments)

說明:繫結函式 function 到物件 object 上, 也就是無論何時呼叫函式, 函式裡的 this 都指向這個 object.任意可選引數 arguments 可以傳遞給函式 function , 可以填充函式所需要的引數,這也被稱為 partial application。對於沒有結合上下文的partial application繫結,請使用partial。

(愚人碼頭注:partial application翻譯成“部分應用”或者“偏函式應用”。partial application可以被描述為一個函式,它接受一定數目的引數,繫結值到一個或多個這些引數,並返回一個新的函式,這個返回函式只接受剩餘未繫結值的引數。參見:http://en.wikipedia.org/wiki/Partial_application。

例子:

var func = function(greeting){ return greeting + ': ' + this.name };

func = _.bind(func, {name: 'moe'}, 'hi');

func();

=> 'hi: moe'

2、bindAll

語法:_.bindAll(object, *methodNames)

說明:把methodNames引數指定的一些方法繫結到object上,這些方法就會在物件的上下文環境中執行。繫結函式用作事件處理函式時非常便利,否則函式被呼叫時this一點用也沒有。methodNames引數是必須的。

例子:

var buttonView = {

  label  : 'underscore',

  onClick: function(){ alert('clicked: ' + this.label); },

  onHover: function(){ console.log('hovering: ' + this.label); }

};

_.bindAll(buttonView, 'onClick', 'onHover');

// When the button is clicked, this.label will have the correct value.

jQuery('#underscore_button').bind('click', buttonView.onClick);

3、partial

語法:_.partial(function, *arguments)

說明:區域性應用一個函式填充在任意個數的 arguments,不改變其動態this值。和bind方法很相近。你可以傳遞_ 給arguments列表來指定一個不預先填充,但在呼叫時提供的引數。

例子:

var subtract = function(a, b) { return b - a; };

sub5 = _.partial(subtract, 5);

sub5(20);

=> 15

// Using a placeholder

subFrom20 = _.partial(subtract, _, 20);

subFrom20(5);

=> 15

4、memoize

語法:_.memoize(function, [hashFunction])

說明:Memoizes方法可以快取某函式的計算結果。對於耗時較長的計算是很有幫助的。如果傳遞了 hashFunction 引數,就用 hashFunction 的返回值作為key儲存函式的計算結果。hashFunction 預設使用function的第一個引數作為key。memoized值的快取可作為返回函式的cache屬性。

例子:

var fibonacci = _.memoize(function(n) {

  return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);

});

5、delay

語法:_.delay(function, wait, *arguments)

說明:類似setTimeout,等待wait毫秒後呼叫function。如果傳遞可選的引數arguments,當函式function執行時, arguments 會作為引數傳入。

例子:

var log = _.bind(console.log, console);

_.delay(log, 1000, 'logged later');

=> 'logged later' // Appears after one second.

6、defer

語法:_.defer(function, *arguments)

說明:延遲呼叫function直到當前呼叫棧清空為止,類似使用延時為0的setTimeout方法。對於執行開銷大的計算和無阻塞UI執行緒的HTML渲染時候非常有用。 如果傳遞arguments引數,當函式function執行時, arguments 會作為引數傳入。

例子:

_.defer(function(){ alert('deferred'); });

// Returns from the function before the alert runs.

7、throttle

語法:_.throttle(function, wait, [options])

說明:建立並返回一個像節流閥一樣的函式,當重複呼叫函式的時候,至少每隔 wait毫秒呼叫一次該函式。對於想控制一些觸發頻率較高的事件有幫助。(愚人碼頭注:詳見:javascript函式的throttle和debounce)

預設情況下,throttle將在你呼叫的第一時間儘快執行這個function,並且,如果你在wait週期內呼叫任意次數的函式,都將盡快的被覆蓋。如果你想禁用第一次首先執行的話,傳遞{leading: false},還有如果你想禁用最後一次執行的話,傳遞{trailing: false}。

例子:

var throttled = _.throttle(updatePosition, 100);

$(window).scroll(throttled);

8、debounce

語法:_.debounce(function, wait, [immediate])

說明:返回 function 函式的防反跳版本, 將延遲函式的執行(真正的執行)在函式最後一次呼叫時刻的 wait 毫秒之後. 對於必須在一些輸入(多是一些使用者操作)停止到達之後執行的行為有幫助。 例如: 渲染一個Markdown格式的評論預覽, 當視窗停止改變大小之後重新計算佈局, 等等.

傳參 immediate 為 true, debounce會在 wait 時間間隔的開始呼叫這個函式 。(愚人碼頭注:並且在 waite 的時間之內,不會再次呼叫。)在類似不小心點了提交按鈕兩下而提交了兩次的情況下很有用。

例子:

var lazyLayout = _.debounce(calculateLayout, 300);

$(window).resize(lazyLayout);

9、once

語法:_.once(function)

說明:建立一個只能呼叫一次的函式。重複呼叫改進的方法也沒有效果,只會返回第一次執行時的結果。 作為初始化函式使用時非常有用, 不用再設一個boolean值來檢查是否已經初始化完成.

例子:

var initialize = _.once(createApplication);

initialize();

initialize();

// Application is only created once.

10、after

語法:_.after(count, function)

說明:建立一個函式, 只有在運行了 count 次之後才有效果. 在處理同組非同步請求返回結果時, 如果你要確保同組裡所有非同步請求完成之後才 執行這個函式, 這將非常有用。

例子:

var renderNotes = _.after(notes.length, render);

_.each(notes, function(note) {

  note.asyncSave({success: renderNotes});

});

// renderNotes is run once, after all notes havesaved.

11、before

語法:_.before(count, function)

說明:建立一個函式,呼叫不超過count 次。 當count已經達到時,最後一個函式呼叫的結果將被記住並返回。

例子:

var monthlyMeeting = _.before(3, askForRaise);

monthlyMeeting();

monthlyMeeting();

monthlyMeeting();

// the result of any subsequent calls is the same as the second call

12、wrap

語法:_.wrap(function, wrapper)

說明:將第一個函式 function 封裝到函式 wrapper 裡面, 並把函式 function 作為第一個引數傳給 wrapper. 這樣可以讓 wrapper 在 function 執行之前和之後 執行程式碼, 調整引數然後附有條件地執行.

例子:

var hello = function(name) { return "hello: " + name; };

hello = _.wrap(hello, function(func) {

  return "before, " + func("moe") + ", after";

});

hello();

=> 'before, hello: moe, after'

13、negate

語法:_.negate(predicate)

說明:返回一個新的predicate函式的否定版本。

例子:

var isFalsy = _.negate(Boolean);

_.find([-2, -1, 0, 1, 2], isFalsy);

=> 0

14、compose

語法:_.compose(*functions)

說明:返回函式集 functions 組合後的複合函式, 也就是一個函式執行完之後把返回的結果再作為引數賦給下一個函式來執行. 以此類推. 在數學裡, 把函式 f(), g(), 和 h() 組合起來可以得到複合函式 f(g(h()))。

例子:

var greet    = function(name){ return "hi: " + name; };

var exclaim  = function(statement){ return statement.toUpperCase() + "!"; };

var welcome = _.compose(greet, exclaim);

welcome('moe');

=> 'hi: MOE!'

五、物件函式(Object Functions)

1、keys

語法:_.keys(object)

說明:檢索object擁有的所有可列舉屬性的名稱。

例子:

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

=> ["one", "two", "three"]

2、allKeys

語法:_.allKeys(object)

說明:檢索object擁有的和繼承的所有屬性的名稱。

例子:

function Stooge(name) {

  this.name = name;

}

Stooge.prototype.silly = true;

_.allKeys(new Stooge("Moe"));

=> ["name", "silly"]

3、values

語法:_.values(object)

說明:返回object物件所有的屬性值。

例子:

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

=> [1, 2, 3]

4、mapObject

語法:_.mapObject(object, iteratee, [context])

說明:它類似於map,但是這用於物件。轉換每個屬性的值。

例子:

_.mapObject({start: 5, end: 12}, function(val, key) {

  return val + 5;

});

=> {start: 10, end: 17}

5、pairs

語法:_.pairs(object)

說明:把一個物件轉變為一個[key, value]形式的陣列。

例子:

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

=> [["one", 1], ["two", 2], ["three", 3]]

6、invert

語法:_.invert(object)

說明:返回一個object副本,使其鍵(keys)和值(values)對換。對於這個操作,必須確保object裡所有的值都是唯一的且可以序列號成字串.

例子:

_.invert({Moe: "Moses", Larry: "Louis", Curly: "Jerome"});

=> {Moses: "Moe", Louis: "Larry", Jerome: "Curly"};

7、create

語法:_.create(prototype, props)

說明:建立具有給定原型的新物件, 可選附加props 作為 own的屬性。 基本上,和Object.create一樣, 但是沒有所有的屬性描述符。

例子:

var moe = _.create(Stooge.prototype, {name: "Moe"});

8、functions

語法:_.functions(object)

說明:返回一個物件裡所有的方法名, 而且是已經排序的 — 也就是說, 物件裡每個方法(屬性值是一個函式)的名稱.

例子:

_.functions(_);

=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...

9、findKey

語法:_.findKey(object, predicate, [context])

說明:Similar to _.findIndex but for keys in objects. Returns the key where the predicate truth test passes or undefined.

例子:

10、extend

語法:_.extend(destination, *sources)

說明:複製source物件中的所有屬性覆蓋到destination物件上,並且返回 destination 物件. 複製是按順序的, 所以後面的物件屬性會把前面的物件屬性覆蓋掉(如果有重複).

例子:

_.extend({name: 'moe'}, {age: 50});

=> {name: 'moe', age: 50}

11、extendOwn

語法:_.extendOwn(destination, *sources)

說明:類似於 extend, 但只複製自己的屬性覆蓋到目標物件。(愚人碼頭注:不包括繼承過來的屬性)

例子:

12、pick

語法:_.pick(object, *keys)

說明:返回一個object副本,只過濾出keys(有效的鍵組成的陣列)引數指定的屬性值。或者接受一個判斷函式,指定挑選哪個key。

例子:

_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');

=> {name: 'moe', age: 50}

_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {

  return _.isNumber(value);

});

=> {age: 50}

13、omit

語法:_.omit(object, *keys)

說明:返回一個object副本,只過濾出除去keys(有效的鍵組成的陣列)引數指定的屬性值。 或者接受一個判斷函式,指定忽略哪個key。

例子:

_.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');

=> {name: 'moe', age: 50}

_.omit({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {

  return _.isNumber(value);

});

=> {name: 'moe', userid: 'moe1'}

14、defaults

語法:_.defaults(object, *defaults)

說明:用defaults物件填充object 中的undefined屬性。 並且返回這個object。一旦這個屬性被填充,再使用defaults方法將不會有任何效果。

例子:

var iceCream = {flavor: "chocolate"};

_.defaults(iceCream, {flavor: "vanilla", sprinkles: "lots"});

=> {flavor: "chocolate", sprinkles: "lots"}

15、clone

語法:_.clone(object)

說明:建立 一個淺複製(淺拷貝)的克隆object。任何巢狀的物件或陣列都通過引用拷貝,不會複製。

例子:

_.clone({name: 'moe'});

=> {name: 'moe'};

16、tap

語法:_.tap(object, interceptor)

說明:用 object作為引數來呼叫函式interceptor,然後返回object。這種方法的主要意圖是作為函式鏈式呼叫 的一環, 為了對此物件執行操作並返回物件本身。

例子:

_.chain([1,2,3,200])

  .filter(function(num) { return num % 2 == 0; })

  .tap(alert)

  .map(function(num) { return num * num })

  .value();

=> // [2, 200] (alerted)

=> [4, 40000]

17、has

語法:_.has(object, key)

說明:物件是否包含給定的鍵嗎?等同於object.hasOwnProperty(key),但是使用hasOwnProperty 函式的一個安全引用,以防意外覆蓋。

例子:

_.has({a: 1, b: 2, c: 3}, "b");

=> true

18、property

語法:_.property(key)

說明:返回一個函式,這個函式返回任何傳入的物件的key屬性。

例子:

var stooge = {name: 'moe'};

'moe' === _.property('name')(stooge);

=> true

19、propertyOf

語法:_.propertyOf(object)

說明:和_.property相反。需要一個物件,並返回一個函式,這個函式將返回一個提供的屬性的值。

例子:

var stooge = {name: 'moe'};

_.propertyOf(stooge)('name');

=> 'moe'

20、matcher

語法:_.matcher(attrs)

說明:返回一個斷言函式,這個函式會給你一個斷言可以用來辨別給定的物件是否匹配attrs指定鍵/值屬性。

例子:

var ready = _.matcher({selected: true, visible: true});

var readyToGoList = _.filter(list, ready);

21、isEqual

語法:_.isEqual(object, other)

說明:執行兩個物件之間的優化深度比較,確定他們是否應被視為相等。

例子:

var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};

var clone  = {name: 'moe', luckyNumbers: [13, 27, 34]};

stooge == clone;

=> false

_.isEqual(stooge, clone);

=> true

22、isMatch

語法:_.isMatch(object, properties)

說明:告訴你properties中的鍵和值是否包含在object中。

例子:

var stooge = {name: 'moe', age: 32};

_.isMatch(stooge, {age: 32});

=> true

23、isEmpty

語法:_.isEmpty(object)

說明:如果object 不包含任何值(沒有可列舉的屬性),返回true。 對於字串和類陣列(array-like)物件,如果length屬性為0,那麼_.isEmpty檢查返回true。

例子:

_.isEmpty([1, 2, 3]);

=> false

_.isEmpty({});

=> true

24、isElement

語法:_.isElement(object)

說明:如果object是一個DOM元素,返回true。

例子:

_.isElement(jQuery('body')[0]);

=> true

25、isArray

語法:_.isArray(object)

說明:如果object是一個數組,返回true。

例子:

(function(){ return _.isArray(arguments); })();

=> false

_.isArray([1,2,3]);

=> true

26、isObject

語法:_.isObject(value)

說明:如果object是一個物件,返回true。需要注意的是JavaScript陣列和函式是物件,字串和數字不是。

例子:

_.isObject({});

=> true

_.isObject(1);

=> false

27、isArguments

語法:_.isArguments(object)

說明:如果object是一個引數物件,返回true。

例子:

(function(){ return _.isArguments(arguments); })(1, 2, 3);

=> true

_.isArguments([1,2,3]);

=> false

28、isFunction

語法:_.isFunction(object)

說明:如果object是一個函式(Function),返回true。

例子:

_.isFunction(alert);

=> true

29、isString

語法:_.isString(object)

說明:如果object是一個字串,返回true。

例子:

_.isString("moe");

=> true

30、isNumber

語法:_.isNumber(object)

說明:如果object是一個數值,返回true (包括 NaN)。

例子:

_.isNumber(8.4 * 5);

=> true

31、isFinite

語法:_.isFinite(object)

說明:如果object是一個有限的數字,返回true。

例子:

_.isFinite(-101);

=> true

_.isFinite(-Infinity);

=> false

32、isBoolean

語法:_.isBoolean(object)

說明:如果object是一個布林值,返回true,否則返回false。

例子:

_.isBoolean(null);

=> false

33、isDate

語法:_.isDate(object)

說明:Returns true if object is a Date.

例子:

_.isDate(new Date());

=> true

34、isRegExp

語法:_.isRegExp(object)

說明:如果object是一個正則表示式,返回true。

例子:

_.isRegExp(/moe/);

=> true

35、isError

語法:_.isError(object)

說明:如果object繼承至 Error 物件,那麼返回 true。

例子:

try {

  throw new TypeError("Example");

} catch (o_O) {

  _.isError(o_O)

}

=> true

36、isNaN

語法:_.isNaN(object)

說明:如果object是 NaN,返回true。

注意: 這和原生的isNaN 函式不一樣,如果變數是undefined,原生的isNaN 函式也會返回 true 。

例子:

_.isNaN(NaN);

=> true

isNaN(undefined);

=> true

_.isNaN(undefined);

=> false

37、isNull

語法:_.isNull(object)

說明:如果object的值是 null,返回true。

例子:

_.isNull(null);

=> true

_.isNull(undefined);

=> false

38、isUndefined

語法:_.isUndefined(value)

說明:如果value是undefined,返回true。

例子:

_.isUndefined(window.missingVariable);

=> true

六、實用功能(Utility Functions)

1、noConflict

語法:_.noConflict()

說明:放棄Underscore 的控制變數"_"。返回Underscore 物件的引用。

例子:

var underscore = _.noConflict();

2、identity

語法:_.identity(value)

說明:返回與傳入引數相等的值. 相當於數學裡的: f(x) = x

這個函式看似無用, 但是在Underscore裡被用作預設的迭代器iterator.

例子:

var stooge = {name: 'moe'};

stooge === _.identity(stooge);

=> true

3、constant

語法:_.constant(value)

說明:建立一個函式,這個函式 返回相同的值 用來作為_.constant的引數。

例子:

var stooge = {name: 'moe'};

stooge === _.constant(stooge)();

=> true

4、noop

語法:_.noop()

說明:返回undefined,不論傳遞給它的是什麼引數。 可以用作預設可選的回撥引數。

例子:

obj.initialize = _.noop;

5、times

語法:_.times(n, iteratee, [context])

說明:呼叫給定的迭代函式n次,每一次呼叫iteratee傳遞index引數。生成一個返回值的陣列。

注意: 本例使用 鏈式語法。

例子:

_(3).times(function(n){ genie.grantWishNumber(n); });

6、random

語法:_.random(min, max)

說明:返回一個min 和 max之間的隨機整數。如果你只傳遞一個引數,那麼將返回0和這個引數之間的整數。

例子:

_.random(0, 100);

=> 42

7、mixin

語法:_.mixin(object)

說明:允許用您自己的實用程式函式擴充套件Underscore。傳遞一個 {name: function}定義的雜湊新增到Underscore物件,以及面向物件封裝。

例子:

_.mixin({

  capitalize: function(string) {

    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();

  }

});

_("fabio").capitalize();

=> "Fabio"

8、iteratee

語法:_.iteratee(value, [context])

說明:一個重要的內部函式用來生成可應用到集合中每個元素的回撥, 返回想要的結果 - 無論是等式,任意回撥,屬性匹配,或屬性訪問。

通過_.iteratee轉換判斷的Underscore 方法的完整列表