PageRenderTime 55ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

https://github.com/fangweiwei/underscore
HTML | 1632 lines | 1461 code | 170 blank | 1 comment | 0 complexity | 565aba13c24de2d1dee900dda0c3d82a MD5 | raw file
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="chrome=1">
  6. <title>Underscore.js</title>
  7. <style>
  8. body {
  9. font-size: 16px;
  10. line-height: 24px;
  11. background: #f0f0e5;
  12. color: #252519;
  13. font-family: "Palatino Linotype", "Book Antiqua", Palatino, FreeSerif, serif;
  14. }
  15. div.container {
  16. width: 720px;
  17. margin: 50px 0 50px 50px;
  18. }
  19. p {
  20. width: 550px;
  21. }
  22. #documentation p {
  23. margin-bottom: 4px;
  24. }
  25. a, a:visited {
  26. padding: 0 2px;
  27. text-decoration: none;
  28. background: #dadaba;
  29. color: #252519;
  30. }
  31. a:active, a:hover {
  32. color: #000;
  33. background: #f0c095;
  34. }
  35. h1, h2, h3, h4, h5, h6 {
  36. margin-top: 40px;
  37. }
  38. b.header {
  39. font-size: 18px;
  40. }
  41. span.alias {
  42. font-size: 14px;
  43. font-style: italic;
  44. margin-left: 20px;
  45. }
  46. table, tr, td {
  47. margin: 0; padding: 0;
  48. }
  49. td {
  50. padding: 2px 12px 2px 0;
  51. }
  52. code, pre, tt {
  53. font-family: Monaco, Consolas, "Lucida Console", monospace;
  54. font-size: 12px;
  55. line-height: 18px;
  56. color: #555529;
  57. }
  58. code {
  59. margin-left: 20px;
  60. }
  61. pre {
  62. font-size: 12px;
  63. padding: 2px 0 2px 12px;
  64. border-left: 6px solid #aaaa99;
  65. margin: 0px 0 30px;
  66. }
  67. </style>
  68. </head>
  69. <body>
  70. <div class="container">
  71. <h1>Underscore.js</h1>
  72. <p>
  73. <a href="http://github.com/documentcloud/underscore/">Underscore</a> is a
  74. utility-belt library for JavaScript that provides a lot of the
  75. functional programming support that you would expect in
  76. <a href="http://prototypejs.org/api">Prototype.js</a>
  77. (or <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">Ruby</a>),
  78. but without extending any of the built-in JavaScript objects. It's the
  79. tie to go along with <a href="http://docs.jquery.com">jQuery</a>'s tux.
  80. </p>
  81. <p>
  82. Underscore provides 60-odd functions that support both the usual
  83. functional suspects: <b>map</b>, <b>select</b>, <b>invoke</b> &mdash;
  84. as well as more specialized helpers: function binding, javascript
  85. templating, deep equality testing, and so on. It delegates to built-in
  86. functions, if present, so modern browsers will use the
  87. native implementations of <b>forEach</b>, <b>map</b>, <b>reduce</b>,
  88. <b>filter</b>, <b>every</b>, <b>some</b> and <b>indexOf</b>.
  89. </p>
  90. <p>
  91. A complete <a href="test/test.html">Test &amp; Benchmark Suite</a>
  92. is included for your perusal.
  93. </p>
  94. <p>
  95. You may also read through the <a href="docs/underscore.html">annotated source code</a>.
  96. </p>
  97. <p>
  98. The project is
  99. <a href="http://github.com/documentcloud/underscore/">hosted on GitHub</a>.
  100. You can report bugs and discuss features on the
  101. <a href="http://github.com/documentcloud/underscore/issues">issues page</a>,
  102. on Freenode in the <tt>#documentcloud</tt> channel,
  103. or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
  104. </p>
  105. <p>
  106. <i>Underscore is an open-source component of <a href="http://documentcloud.org/">DocumentCloud</a>.</i>
  107. </p>
  108. <h2>Downloads <i style="padding-left: 12px; font-size:12px;">(Right-click, and use "Save As")</i></h2>
  109. <table>
  110. <tr>
  111. <td><a href="underscore.js">Development Version (1.1.7)</a></td>
  112. <td><i>28kb, Uncompressed with Comments</i></td>
  113. </tr>
  114. <tr>
  115. <td><a href="underscore-min.js">Production Version (1.1.7)</a></td>
  116. <td><i>3kb, Minified and Gzipped</i></td>
  117. </tr>
  118. </table>
  119. <h2>Table of Contents</h2>
  120. <a href="#styles">Object-Oriented and Functional Styles</a>
  121. <p>
  122. <b>Collections</b>
  123. <br />
  124. <span class="methods"><a href="#each">each</a>, <a href="#map">map</a>,
  125. <a href="#reduce">reduce</a>, <a href="#reduceRight">reduceRight</a>,
  126. <a href="#detect">detect</a>, <a href="#select">select</a>,
  127. <a href="#reject">reject</a>, <a href="#all">all</a>,
  128. <a href="#any">any</a>, <a href="#include">include</a>,
  129. <a href="#invoke">invoke</a>, <a href="#pluck">pluck</a>,
  130. <a href="#max">max</a>, <a href="#min">min</a>,
  131. <a href="#sortBy">sortBy</a>, <a href="#groupBy">groupBy</a>, <a href="#sortedIndex">sortedIndex</a>,
  132. <a href="#toArray">toArray</a>, <a href="#size">size</a></span>
  133. </p>
  134. <p>
  135. <b>Arrays</b>
  136. <br />
  137. <span class="methods"><a href="#first">first</a>, <a href="#rest">rest</a>, <a href="#last">last</a>,
  138. <a href="#compact">compact</a>, <a href="#flatten">flatten</a>, <a href="#without">without</a>,
  139. <a href="#union">union</a>, <a href="#intersection">intersection</a>, <a href="#difference">difference</a>,
  140. <a href="#uniq">uniq</a>, <a href="#zip">zip</a>, <a href="#indexOf">indexOf</a>,
  141. <a href="#lastIndexOf">lastIndexOf</a>, <a href="#range">range</a></span>
  142. </p>
  143. <p>
  144. <b>Functions</b>
  145. <br />
  146. <span class="methods"><a href="#bind">bind</a>, <a href="#bindAll">bindAll</a>,
  147. <a href="#memoize">memoize</a>, <a href="#delay">delay</a>, <a href="#defer">defer</a>,
  148. <a href="#throttle">throttle</a>, <a href="#debounce">debounce</a>,
  149. <a href="#once">once</a>, <a href="#after">after</a>, <a href="#wrap">wrap</a>, <a href="#compose">compose</a></span>
  150. </p>
  151. <p>
  152. <b>Objects</b>
  153. <br />
  154. <span class="methods"><a href="#keys">keys</a>, <a href="#values">values</a>,
  155. <a href="#functions">functions</a>, <a href="#extend">extend</a>, <a href="#defaults">defaults</a>, <a href="#clone">clone</a>, <a href="#tap">tap</a>,
  156. <a href="#isEqual">isEqual</a>, <a href="#isEmpty">isEmpty</a>, <a href="#isElement">isElement</a>,
  157. <a href="#isArray">isArray</a>, <a href="#isArguments">isArguments</a>, <a href="#isFunction">isFunction</a>, <a href="#isString">isString</a>,
  158. <a href="#isNumber">isNumber</a>, <a href="#isBoolean">isBoolean</a>, <a href="#isDate">isDate</a>, <a href="#isRegExp">isRegExp</a>
  159. <a href="#isNaN">isNaN</a>, <a href="#isNull">isNull</a>,
  160. <a href="#isUndefined">isUndefined</a>
  161. </span>
  162. </p>
  163. <p>
  164. <b>Utility</b>
  165. <br />
  166. <span class="methods"><a href="#noConflict">noConflict</a>,
  167. <a href="#identity">identity</a>, <a href="#times">times</a>,
  168. <a href="#mixin">mixin</a>, <a href="#uniqueId">uniqueId</a>,
  169. <a href="#template">template</a></span>
  170. </p>
  171. <p>
  172. <b>Chaining</b>
  173. <br />
  174. <span class="methods"><a href="#chain">chain</a>, <a href="#value">value</a>
  175. </p>
  176. <div id="documentation">
  177. <h2 id="styles">Object-Oriented and Functional Styles</h2>
  178. <p>
  179. You can use Underscore in either an object-oriented or a functional style,
  180. depending on your preference. The following two lines of code are
  181. identical ways to double a list of numbers.
  182. </p>
  183. <pre>
  184. _.map([1, 2, 3], function(n){ return n * 2; });
  185. _([1, 2, 3]).map(function(n){ return n * 2; });</pre>
  186. <p>
  187. Using the object-oriented style allows you to chain together methods. Calling
  188. <tt>chain</tt> on a wrapped object will cause all future method calls to
  189. return wrapped objects as well. When you've finished the computation,
  190. use <tt>value</tt> to retrieve the final value. Here's an example of chaining
  191. together a <b>map/flatten/reduce</b>, in order to get the word count of
  192. every word in a song.
  193. </p>
  194. <pre>
  195. var lyrics = [
  196. {line : 1, words : "I'm a lumberjack and I'm okay"},
  197. {line : 2, words : "I sleep all night and I work all day"},
  198. {line : 3, words : "He's a lumberjack and he's okay"},
  199. {line : 4, words : "He sleeps all night and he works all day"}
  200. ];
  201. _(lyrics).chain()
  202. .map(function(line) { return line.words.split(' '); })
  203. .flatten()
  204. .reduce(function(counts, word) {
  205. counts[word] = (counts[word] || 0) + 1;
  206. return counts;
  207. }, {}).value();
  208. =&gt; {lumberjack : 2, all : 4, night : 2 ... }</pre>
  209. <p>
  210. In addition, the
  211. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/prototype">Array prototype's methods</a>
  212. are proxied through the chained Underscore object, so you can slip a
  213. <tt>reverse</tt> or a <tt>push</tt> into your chain, and continue to
  214. modify the array.
  215. </p>
  216. <h2>Collection Functions (Arrays or Objects)</h2>
  217. <p id="each">
  218. <b class="header">each</b><code>_.each(list, iterator, [context])</code>
  219. <span class="alias">Alias: <b>forEach</b></span>
  220. <br />
  221. Iterates over a <b>list</b> of elements, yielding each in turn to an <b>iterator</b>
  222. function. The <b>iterator</b> is bound to the <b>context</b> object, if one is
  223. passed. Each invocation of <b>iterator</b> is called with three arguments:
  224. <tt>(element, index, list)</tt>. If <b>list</b> is a JavaScript object, <b>iterator</b>'s
  225. arguments will be <tt>(value, key, list)</tt>. Delegates to the native
  226. <b>forEach</b> function if it exists.
  227. </p>
  228. <pre>
  229. _.each([1, 2, 3], function(num){ alert(num); });
  230. =&gt; alerts each number in turn...
  231. _.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); });
  232. =&gt; alerts each number in turn...</pre>
  233. <p id="map">
  234. <b class="header">map</b><code>_.map(list, iterator, [context])</code>
  235. <br />
  236. Produces a new array of values by mapping each value in <b>list</b>
  237. through a transformation function (<b>iterator</b>). If the native <b>map</b> method
  238. exists, it will be used instead. If <b>list</b> is a JavaScript object,
  239. <b>iterator</b>'s arguments will be <tt>(value, key, list)</tt>.
  240. </p>
  241. <pre>
  242. _.map([1, 2, 3], function(num){ return num * 3; });
  243. =&gt; [3, 6, 9]
  244. _.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; });
  245. =&gt; [3, 6, 9]</pre>
  246. <p id="reduce">
  247. <b class="header">reduce</b><code>_.reduce(list, iterator, memo, [context])</code>
  248. <span class="alias">Aliases: <b>inject, foldl</b></span>
  249. <br />
  250. Also known as <b>inject</b> and <b>foldl</b>, <b>reduce</b> boils down a
  251. <b>list</b> of values into a single value. <b>Memo</b> is the initial state
  252. of the reduction, and each successive step of it should be returned by
  253. <b>iterator</b>.
  254. </p>
  255. <pre>
  256. var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
  257. =&gt; 6
  258. </pre>
  259. <p id="reduceRight">
  260. <b class="header">reduceRight</b><code>_.reduceRight(list, iterator, memo, [context])</code>
  261. <span class="alias">Alias: <b>foldr</b></span>
  262. <br />
  263. The right-associative version of <b>reduce</b>. Delegates to the
  264. JavaScript 1.8 version of <b>reduceRight</b>, if it exists. <b>Foldr</b>
  265. is not as useful in JavaScript as it would be in a language with lazy
  266. evaluation.
  267. </p>
  268. <pre>
  269. var list = [[0, 1], [2, 3], [4, 5]];
  270. var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  271. =&gt; [4, 5, 2, 3, 0, 1]
  272. </pre>
  273. <p id="detect">
  274. <b class="header">detect</b><code>_.detect(list, iterator, [context])</code>
  275. <br />
  276. Looks through each value in the <b>list</b>, returning the first one that
  277. passes a truth test (<b>iterator</b>). The function returns as
  278. soon as it finds an acceptable element, and doesn't traverse the
  279. entire list.
  280. </p>
  281. <pre>
  282. var even = _.detect([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  283. =&gt; 2
  284. </pre>
  285. <p id="select">
  286. <b class="header">select</b><code>_.select(list, iterator, [context])</code>
  287. <span class="alias">Alias: <b>filter</b></span>
  288. <br />
  289. Looks through each value in the <b>list</b>, returning an array of all
  290. the values that pass a truth test (<b>iterator</b>). Delegates to the
  291. native <b>filter</b> method, if it exists.
  292. </p>
  293. <pre>
  294. var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  295. =&gt; [2, 4, 6]
  296. </pre>
  297. <p id="reject">
  298. <b class="header">reject</b><code>_.reject(list, iterator, [context])</code>
  299. <br />
  300. Returns the values in <b>list</b> without the elements that the truth
  301. test (<b>iterator</b>) passes. The opposite of <b>select</b>.
  302. </p>
  303. <pre>
  304. var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  305. =&gt; [1, 3, 5]
  306. </pre>
  307. <p id="all">
  308. <b class="header">all</b><code>_.all(list, iterator, [context])</code>
  309. <span class="alias">Alias: <b>every</b></span>
  310. <br />
  311. Returns <i>true</i> if all of the values in the <b>list</b> pass the <b>iterator</b>
  312. truth test. Delegates to the native method <b>every</b>, if present.
  313. </p>
  314. <pre>
  315. _.all([true, 1, null, 'yes'], _.identity);
  316. =&gt; false
  317. </pre>
  318. <p id="any">
  319. <b class="header">any</b><code>_.any(list, [iterator], [context])</code>
  320. <span class="alias">Alias: <b>some</b></span>
  321. <br />
  322. Returns <i>true</i> if any of the values in the <b>list</b> pass the
  323. <b>iterator</b> truth test. Short-circuits and stops traversing the list
  324. if a true element is found. Delegates to the native method <b>some</b>,
  325. if present.
  326. </p>
  327. <pre>
  328. _.any([null, 0, 'yes', false]);
  329. =&gt; true
  330. </pre>
  331. <p id="include">
  332. <b class="header">include</b><code>_.include(list, value)</code>
  333. <span class="alias">Alias: <b>contains</b></span>
  334. <br />
  335. Returns <i>true</i> if the <b>value</b> is present in the <b>list</b>, using
  336. <i>===</i> to test equality. Uses <b>indexOf</b> internally, if <b>list</b>
  337. is an Array.
  338. </p>
  339. <pre>
  340. _.include([1, 2, 3], 3);
  341. =&gt; true
  342. </pre>
  343. <p id="invoke">
  344. <b class="header">invoke</b><code>_.invoke(list, methodName, [*arguments])</code>
  345. <br />
  346. Calls the method named by <b>methodName</b> on each value in the <b>list</b>.
  347. Any extra arguments passed to <b>invoke</b> will be forwarded on to the
  348. method invocation.
  349. </p>
  350. <pre>
  351. _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  352. =&gt; [[1, 5, 7], [1, 2, 3]]
  353. </pre>
  354. <p id="pluck">
  355. <b class="header">pluck</b><code>_.pluck(list, propertyName)</code>
  356. <br />
  357. A convenient version of what is perhaps the most common use-case for
  358. <b>map</b>: extracting a list of property values.
  359. </p>
  360. <pre>
  361. var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
  362. _.pluck(stooges, 'name');
  363. =&gt; ["moe", "larry", "curly"]
  364. </pre>
  365. <p id="max">
  366. <b class="header">max</b><code>_.max(list, [iterator], [context])</code>
  367. <br />
  368. Returns the maximum value in <b>list</b>. If <b>iterator</b> is passed,
  369. it will be used on each value to generate the criterion by which the
  370. value is ranked.
  371. </p>
  372. <pre>
  373. var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
  374. _.max(stooges, function(stooge){ return stooge.age; });
  375. =&gt; {name : 'curly', age : 60};
  376. </pre>
  377. <p id="min">
  378. <b class="header">min</b><code>_.min(list, [iterator], [context])</code>
  379. <br />
  380. Returns the minimum value in <b>list</b>. If <b>iterator</b> is passed,
  381. it will be used on each value to generate the criterion by which the
  382. value is ranked.
  383. </p>
  384. <pre>
  385. var numbers = [10, 5, 100, 2, 1000];
  386. _.min(numbers);
  387. =&gt; 2
  388. </pre>
  389. <p id="sortBy">
  390. <b class="header">sortBy</b><code>_.sortBy(list, iterator, [context])</code>
  391. <br />
  392. Returns a sorted copy of <b>list</b>, ranked by the results of running
  393. each value through <b>iterator</b>.
  394. </p>
  395. <pre>
  396. _.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
  397. =&gt; [5, 4, 6, 3, 1, 2]
  398. </pre>
  399. <p id="groupBy">
  400. <b class="header">groupBy</b><code>_.groupBy(list, iterator)</code>
  401. <br />
  402. Splits a collection into sets, grouped by the result of running each
  403. value through <b>iterator</b>.
  404. </p>
  405. <pre>
  406. _.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
  407. =&gt; {1: [1.3], 2: [2.1, 2.4]}
  408. </pre>
  409. <p id="sortedIndex">
  410. <b class="header">sortedIndex</b><code>_.sortedIndex(list, value, [iterator])</code>
  411. <br />
  412. Uses a binary search to determine the index at which the <b>value</b>
  413. <i>should</i> be inserted into the <b>list</b> in order to maintain the <b>list</b>'s
  414. sorted order. If an <b>iterator</b> is passed, it will be used to compute
  415. the sort ranking of each value.
  416. </p>
  417. <pre>
  418. _.sortedIndex([10, 20, 30, 40, 50], 35);
  419. =&gt; 3
  420. </pre>
  421. <p id="toArray">
  422. <b class="header">toArray</b><code>_.toArray(list)</code>
  423. <br />
  424. Converts the <b>list</b> (anything that can be iterated over), into a
  425. real Array. Useful for transmuting the <b>arguments</b> object.
  426. </p>
  427. <pre>
  428. (function(){ return _.toArray(arguments).slice(0); })(1, 2, 3);
  429. =&gt; [1, 2, 3]
  430. </pre>
  431. <p id="size">
  432. <b class="header">size</b><code>_.size(list)</code>
  433. <br />
  434. Return the number of values in the <b>list</b>.
  435. </p>
  436. <pre>
  437. _.size({one : 1, two : 2, three : 3});
  438. =&gt; 3
  439. </pre>
  440. <h2>Array Functions</h2>
  441. <p>
  442. <i>Note: All array functions will also work on the <b>arguments</b> object.</i>
  443. </p>
  444. <p id="first">
  445. <b class="header">first</b><code>_.first(array, [n])</code>
  446. <span class="alias">Alias: <b>head</b></span>
  447. <br />
  448. Returns the first element of an <b>array</b>. Passing <b>n</b> will
  449. return the first <b>n</b> elements of the array.
  450. </p>
  451. <pre>
  452. _.first([5, 4, 3, 2, 1]);
  453. =&gt; 5
  454. </pre>
  455. <p id="rest">
  456. <b class="header">rest</b><code>_.rest(array, [index])</code>
  457. <span class="alias">Alias: <b>tail</b></span>
  458. <br />
  459. Returns the <b>rest</b> of the elements in an array. Pass an <b>index</b>
  460. to return the values of the array from that index onward.
  461. </p>
  462. <pre>
  463. _.rest([5, 4, 3, 2, 1]);
  464. =&gt; [4, 3, 2, 1]
  465. </pre>
  466. <p id="last">
  467. <b class="header">last</b><code>_.last(array)</code>
  468. <br />
  469. Returns the last element of an <b>array</b>.
  470. </p>
  471. <pre>
  472. _.last([5, 4, 3, 2, 1]);
  473. =&gt; 1
  474. </pre>
  475. <p id="compact">
  476. <b class="header">compact</b><code>_.compact(array)</code>
  477. <br />
  478. Returns a copy of the <b>array</b> with all falsy values removed.
  479. In JavaScript, <i>false</i>, <i>null</i>, <i>0</i>, <i>""</i>,
  480. <i>undefined</i> and <i>NaN</i> are all falsy.
  481. </p>
  482. <pre>
  483. _.compact([0, 1, false, 2, '', 3]);
  484. =&gt; [1, 2, 3]
  485. </pre>
  486. <p id="flatten">
  487. <b class="header">flatten</b><code>_.flatten(array)</code>
  488. <br />
  489. Flattens a nested <b>array</b> (the nesting can be to any depth).
  490. </p>
  491. <pre>
  492. _.flatten([1, [2], [3, [[[4]]]]]);
  493. =&gt; [1, 2, 3, 4];
  494. </pre>
  495. <p id="without">
  496. <b class="header">without</b><code>_.without(array, [*values])</code>
  497. <br />
  498. Returns a copy of the <b>array</b> with all instances of the <b>values</b>
  499. removed. <i>===</i> is used for the equality test.
  500. </p>
  501. <pre>
  502. _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
  503. =&gt; [2, 3, 4]
  504. </pre>
  505. <p id="union">
  506. <b class="header">union</b><code>_.union(*arrays)</code>
  507. <br />
  508. Computes the union of the passed-in <b>arrays</b>: the list of unique items,
  509. in order, that are present in one or more of the <b>arrays</b>.
  510. </p>
  511. <pre>
  512. _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  513. =&gt; [1, 2, 3, 101, 10]
  514. </pre>
  515. <p id="intersection">
  516. <b class="header">intersection</b><code>_.intersection(*arrays)</code>
  517. <br />
  518. Computes the list of values that are the intersection of all the <b>arrays</b>.
  519. Each value in the result is present in each of the <b>arrays</b>.
  520. </p>
  521. <pre>
  522. _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  523. =&gt; [1, 2]
  524. </pre>
  525. <p id="difference">
  526. <b class="header">difference</b><code>_.difference(array, other)</code>
  527. <br />
  528. Similar to <b>without</b>, but returns the values from <b>array</b> that
  529. are not present in <b>other</b>.
  530. </p>
  531. <pre>
  532. _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  533. =&gt; [1, 3, 4]
  534. </pre>
  535. <p id="uniq">
  536. <b class="header">uniq</b><code>_.uniq(array, [isSorted], [iterator])</code>
  537. <span class="alias">Alias: <b>unique</b></span>
  538. <br />
  539. Produces a duplicate-free version of the <b>array</b>, using <i>===</i> to test
  540. object equality. If you know in advance that the <b>array</b> is sorted,
  541. passing <i>true</i> for <b>isSorted</b> will run a much faster algorithm.
  542. If you want to compute unique items based on a transformation, pass an
  543. <b>iterator</b> function.
  544. </p>
  545. <pre>
  546. _.uniq([1, 2, 1, 3, 1, 4]);
  547. =&gt; [1, 2, 3, 4]
  548. </pre>
  549. <p id="zip">
  550. <b class="header">zip</b><code>_.zip(*arrays)</code>
  551. <br />
  552. Merges together the values of each of the <b>arrays</b> with the
  553. values at the corresponding position. Useful when you have separate
  554. data sources that are coordinated through matching array indexes.
  555. If you're working with a matrix of nested arrays, <b>zip.apply</b>
  556. can transpose the matrix in a similar fashion.
  557. </p>
  558. <pre>
  559. _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
  560. =&gt; [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
  561. </pre>
  562. <p id="indexOf">
  563. <b class="header">indexOf</b><code>_.indexOf(array, value, [isSorted])</code>
  564. <br />
  565. Returns the index at which <b>value</b> can be found in the <b>array</b>,
  566. or <i>-1</i> if value is not present in the <b>array</b>. Uses the native
  567. <b>indexOf</b> function unless it's missing. If you're working with a
  568. large array, and you know that the array is already sorted, pass <tt>true</tt>
  569. for <b>isSorted</b> to use a faster binary search.
  570. </p>
  571. <pre>
  572. _.indexOf([1, 2, 3], 2);
  573. =&gt; 1
  574. </pre>
  575. <p id="lastIndexOf">
  576. <b class="header">lastIndexOf</b><code>_.lastIndexOf(array, value)</code>
  577. <br />
  578. Returns the index of the last occurrence of <b>value</b> in the <b>array</b>,
  579. or <i>-1</i> if value is not present. Uses the native <b>lastIndexOf</b>
  580. function if possible.
  581. </p>
  582. <pre>
  583. _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  584. =&gt; 4
  585. </pre>
  586. <p id="range">
  587. <b class="header">range</b><code>_.range([start], stop, [step])</code>
  588. <br />
  589. A function to create flexibly-numbered lists of integers, handy for
  590. <tt>each</tt> and <tt>map</tt> loops. <b>start</b>, if omitted, defaults
  591. to <i>0</i>; <b>step</b> defaults to <i>1</i>. Returns a list of integers
  592. from <b>start</b> to <b>stop</b>, incremented (or decremented) by <b>step</b>,
  593. exclusive.
  594. </p>
  595. <pre>
  596. _.range(10);
  597. =&gt; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  598. _.range(1, 11);
  599. =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  600. _.range(0, 30, 5);
  601. =&gt; [0, 5, 10, 15, 20, 25]
  602. _.range(0, -10, -1);
  603. =&gt; [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  604. _.range(0);
  605. =&gt; []
  606. </pre>
  607. <h2>Function (uh, ahem) Functions</h2>
  608. <p id="bind">
  609. <b class="header">bind</b><code>_.bind(function, object, [*arguments])</code>
  610. <br />
  611. Bind a <b>function</b> to an <b>object</b>, meaning that whenever
  612. the function is called, the value of <i>this</i> will be the <b>object</b>.
  613. Optionally, bind <b>arguments</b> to the <b>function</b> to pre-fill them,
  614. also known as <b>currying</b>.
  615. </p>
  616. <pre>
  617. var func = function(greeting){ return greeting + ': ' + this.name };
  618. func = _.bind(func, {name : 'moe'}, 'hi');
  619. func();
  620. =&gt; 'hi: moe'
  621. </pre>
  622. <p id="bindAll">
  623. <b class="header">bindAll</b><code>_.bindAll(object, [*methodNames])</code>
  624. <br />
  625. Binds a number of methods on the <b>object</b>, specified by
  626. <b>methodNames</b>, to be run in the context of that object whenever they
  627. are invoked. Very handy for binding functions that are going to be used
  628. as event handlers, which would otherwise be invoked with a fairly useless
  629. <i>this</i>. If no <b>methodNames</b> are provided, all of the object's
  630. function properties will be bound to it.
  631. </p>
  632. <pre>
  633. var buttonView = {
  634. label : 'underscore',
  635. onClick : function(){ alert('clicked: ' + this.label); },
  636. onHover : function(){ console.log('hovering: ' + this.label); }
  637. };
  638. _.bindAll(buttonView);
  639. jQuery('#underscore_button').bind('click', buttonView.onClick);
  640. =&gt; When the button is clicked, this.label will have the correct value...
  641. </pre>
  642. <p id="memoize">
  643. <b class="header">memoize</b><code>_.memoize(function, [hashFunction])</code>
  644. <br />
  645. Memoizes a given <b>function</b> by caching the computed result. Useful
  646. for speeding up slow-running computations. If passed an optional
  647. <b>hashFunction</b>, it will be used to compute the hash key for storing
  648. the result, based on the arguments to the original function. The default
  649. <b>hashFunction</b> just uses the first argument to the memoized function
  650. as the key.
  651. </p>
  652. <pre>
  653. var fibonacci = function(n) {
  654. return n &lt; 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  655. };
  656. var fastFibonacci = _.memoize(fibonacci);
  657. </pre>
  658. <p id="delay">
  659. <b class="header">delay</b><code>_.delay(function, wait, [*arguments])</code>
  660. <br />
  661. Much like <b>setTimeout</b>, invokes <b>function</b> after <b>wait</b>
  662. milliseconds. If you pass the optional <b>arguments</b>, they will be
  663. forwarded on to the <b>function</b> when it is invoked.
  664. </p>
  665. <pre>
  666. var log = _.bind(console.log, console);
  667. _.delay(log, 1000, 'logged later');
  668. =&gt; 'logged later' // Appears after one second.
  669. </pre>
  670. <p id="defer">
  671. <b class="header">defer</b><code>_.defer(function)</code>
  672. <br />
  673. Defers invoking the <b>function</b> until the current call stack has cleared,
  674. similar to using <b>setTimeout</b> with a delay of 0. Useful for performing
  675. expensive computations or HTML rendering in chunks without blocking the UI thread
  676. from updating.
  677. </p>
  678. <pre>
  679. _.defer(function(){ alert('deferred'); });
  680. // Returns from the function before the alert runs.
  681. </pre>
  682. <p id="throttle">
  683. <b class="header">throttle</b><code>_.throttle(function, wait)</code>
  684. <br />
  685. Returns a throttled version of the function, that, when invoked repeatedly,
  686. will only actually call the wrapped function at most once per every <b>wait</b>
  687. milliseconds. Useful for rate-limiting events that occur faster than you
  688. can keep up with.
  689. </p>
  690. <pre>
  691. var throttled = _.throttle(updatePosition, 100);
  692. $(window).scroll(throttled);
  693. </pre>
  694. <p id="debounce">
  695. <b class="header">debounce</b><code>_.debounce(function, wait)</code>
  696. <br />
  697. Repeated calls to a debounced function will postpone it's execution
  698. until after <b>wait</b> milliseconds have elapsed. Useful for implementing
  699. behavior that should only happen <i>after</i> the input has stopped arriving.
  700. For example: rendering a preview of a Markdown comment, recalculating a
  701. layout after the window has stopped being resized...
  702. </p>
  703. <pre>
  704. var lazyLayout = _.debounce(calculateLayout, 300);
  705. $(window).resize(lazyLayout);
  706. </pre>
  707. <p id="once">
  708. <b class="header">once</b><code>_.once(function)</code>
  709. <br />
  710. Creates a version of the function that can only be called one time.
  711. Repeated calls to the modified function will have no effect, returning
  712. the value from the original call. Useful for initialization functions,
  713. instead of having to set a boolean flag and then check it later.
  714. </p>
  715. <pre>
  716. var initialize = _.once(createApplication);
  717. initialize();
  718. initialize();
  719. // Application is only created once.
  720. </pre>
  721. <p id="after">
  722. <b class="header">after</b><code>_.after(count, function)</code>
  723. <br />
  724. Creates a version of the function that will only be run after first
  725. being called <b>count</b> times. Useful for grouping asynchronous responses,
  726. where you want to be sure that all the async calls have finished, before
  727. proceeding.
  728. </p>
  729. <pre>
  730. var renderNotes = _.after(notes.length, render);
  731. _.each(notes, function(note) {
  732. note.asyncSave({success: renderNotes});
  733. });
  734. // renderNotes is run once, after all notes have saved.
  735. </pre>
  736. <p id="wrap">
  737. <b class="header">wrap</b><code>_.wrap(function, wrapper)</code>
  738. <br />
  739. Wraps the first <b>function</b> inside of the <b>wrapper</b> function,
  740. passing it as the first argument. This allows the <b>wrapper</b> to
  741. execute code before and after the <b>function</b> runs, adjust the arguments,
  742. and execute it conditionally.
  743. </p>
  744. <pre>
  745. var hello = function(name) { return "hello: " + name; };
  746. hello = _.wrap(hello, function(func) {
  747. return "before, " + func("moe") + ", after";
  748. });
  749. hello();
  750. =&gt; 'before, hello: moe, after'
  751. </pre>
  752. <p id="compose">
  753. <b class="header">compose</b><code>_.compose(*functions)</code>
  754. <br />
  755. Returns the composition of a list of <b>functions</b>, where each function
  756. consumes the return value of the function that follows. In math terms,
  757. composing the functions <i>f()</i>, <i>g()</i>, and <i>h()</i> produces
  758. <i>f(g(h()))</i>.
  759. </p>
  760. <pre>
  761. var greet = function(name){ return "hi: " + name; };
  762. var exclaim = function(statement){ return statement + "!"; };
  763. var welcome = _.compose(exclaim, greet);
  764. welcome('moe');
  765. =&gt; 'hi: moe!'
  766. </pre>
  767. <h2>Object Functions</h2>
  768. <p id="keys">
  769. <b class="header">keys</b><code>_.keys(object)</code>
  770. <br />
  771. Retrieve all the names of the <b>object</b>'s properties.
  772. </p>
  773. <pre>
  774. _.keys({one : 1, two : 2, three : 3});
  775. =&gt; ["one", "two", "three"]
  776. </pre>
  777. <p id="values">
  778. <b class="header">values</b><code>_.values(object)</code>
  779. <br />
  780. Return all of the values of the <b>object</b>'s properties.
  781. </p>
  782. <pre>
  783. _.values({one : 1, two : 2, three : 3});
  784. =&gt; [1, 2, 3]
  785. </pre>
  786. <p id="functions">
  787. <b class="header">functions</b><code>_.functions(object)</code>
  788. <span class="alias">Alias: <b>methods</b></span>
  789. <br />
  790. Returns a sorted list of the names of every method in an object &mdash;
  791. that is to say, the name of every function property of the object.
  792. </p>
  793. <pre>
  794. _.functions(_);
  795. =&gt; ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...
  796. </pre>
  797. <p id="extend">
  798. <b class="header">extend</b><code>_.extend(destination, *sources)</code>
  799. <br />
  800. Copy all of the properties in the <b>source</b> objects over to the
  801. <b>destination</b> object. It's in-order, to the last source will override
  802. properties of the same name in previous arguments.
  803. </p>
  804. <pre>
  805. _.extend({name : 'moe'}, {age : 50});
  806. =&gt; {name : 'moe', age : 50}
  807. </pre>
  808. <p id="defaults">
  809. <b class="header">defaults</b><code>_.defaults(object, *defaults)</code>
  810. <br />
  811. Fill in missing properties in <b>object</b> with default values from the
  812. <b>defaults</b> objects. As soon as the property is filled, further defaults
  813. will have no effect.
  814. </p>
  815. <pre>
  816. var iceCream = {flavor : "chocolate"};
  817. _.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"});
  818. =&gt; {flavor : "chocolate", sprinkles : "lots"}
  819. </pre>
  820. <p id="clone">
  821. <b class="header">clone</b><code>_.clone(object)</code>
  822. <br />
  823. Create a shallow-copied clone of the <b>object</b>. Any nested objects
  824. or arrays will be copied by reference, not duplicated.
  825. </p>
  826. <pre>
  827. _.clone({name : 'moe'});
  828. =&gt; {name : 'moe'};
  829. </pre>
  830. <p id="tap">
  831. <b class="header">tap</b><code>_.tap(object, interceptor)</code>
  832. <br />
  833. Invokes <b>interceptor</b> with the <b>object</b>, and then returns <b>object</b>.
  834. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
  835. </p>
  836. <pre>
  837. _([1,2,3,200]).chain().
  838. select(function(num) { return num % 2 == 0; }).
  839. tap(console.log).
  840. map(function(num) { return num * num }).
  841. value();
  842. =&gt; [2, 200]
  843. =&gt; [4, 40000]
  844. </pre>
  845. <p id="isEqual">
  846. <b class="header">isEqual</b><code>_.isEqual(object, other)</code>
  847. <br />
  848. Performs an optimized deep comparison between the two objects, to determine
  849. if they should be considered equal.
  850. </p>
  851. <pre>
  852. var moe = {name : 'moe', luckyNumbers : [13, 27, 34]};
  853. var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
  854. moe == clone;
  855. =&gt; false
  856. _.isEqual(moe, clone);
  857. =&gt; true
  858. </pre>
  859. <p id="isEmpty">
  860. <b class="header">isEmpty</b><code>_.isEmpty(object)</code>
  861. <br />
  862. Returns <i>true</i> if <b>object</b> contains no values.
  863. </p>
  864. <pre>
  865. _.isEmpty([1, 2, 3]);
  866. =&gt; false
  867. _.isEmpty({});
  868. =&gt; true
  869. </pre>
  870. <p id="isElement">
  871. <b class="header">isElement</b><code>_.isElement(object)</code>
  872. <br />
  873. Returns <i>true</i> if <b>object</b> is a DOM element.
  874. </p>
  875. <pre>
  876. _.isElement(jQuery('body')[0]);
  877. =&gt; true
  878. </pre>
  879. <p id="isArray">
  880. <b class="header">isArray</b><code>_.isArray(object)</code>
  881. <br />
  882. Returns <i>true</i> if <b>object</b> is an Array.
  883. </p>
  884. <pre>
  885. (function(){ return _.isArray(arguments); })();
  886. =&gt; false
  887. _.isArray([1,2,3]);
  888. =&gt; true
  889. </pre>
  890. <p id="isArguments">
  891. <b class="header">isArguments</b><code>_.isArguments(object)</code>
  892. <br />
  893. Returns <i>true</i> if <b>object</b> is an Arguments object.
  894. </p>
  895. <pre>
  896. (function(){ return _.isArguments(arguments); })(1, 2, 3);
  897. =&gt; true
  898. _.isArguments([1,2,3]);
  899. =&gt; false
  900. </pre>
  901. <p id="isFunction">
  902. <b class="header">isFunction</b><code>_.isFunction(object)</code>
  903. <br />
  904. Returns <i>true</i> if <b>object</b> is a Function.
  905. </p>
  906. <pre>
  907. _.isFunction(alert);
  908. =&gt; true
  909. </pre>
  910. <p id="isString">
  911. <b class="header">isString</b><code>_.isString(object)</code>
  912. <br />
  913. Returns <i>true</i> if <b>object</b> is a String.
  914. </p>
  915. <pre>
  916. _.isString("moe");
  917. =&gt; true
  918. </pre>
  919. <p id="isNumber">
  920. <b class="header">isNumber</b><code>_.isNumber(object)</code>
  921. <br />
  922. Returns <i>true</i> if <b>object</b> is a Number.
  923. </p>
  924. <pre>
  925. _.isNumber(8.4 * 5);
  926. =&gt; true
  927. </pre>
  928. <p id="isBoolean">
  929. <b class="header">isBoolean</b><code>_.isBoolean(object)</code>
  930. <br />
  931. Returns <i>true</i> if <b>object</b> is either <i>true</i> or <i>false</i>.
  932. </p>
  933. <pre>
  934. _.isBoolean(null);
  935. =&gt; false
  936. </pre>
  937. <p id="isDate">
  938. <b class="header">isDate</b><code>_.isDate(object)</code>
  939. <br />
  940. Returns <i>true</i> if <b>object</b> is a Date.
  941. </p>
  942. <pre>
  943. _.isDate(new Date());
  944. =&gt; true
  945. </pre>
  946. <p id="isRegExp">
  947. <b class="header">isRegExp</b><code>_.isRegExp(object)</code>
  948. <br />
  949. Returns <i>true</i> if <b>object</b> is a RegExp.
  950. </p>
  951. <pre>
  952. _.isRegExp(/moe/);
  953. =&gt; true
  954. </pre>
  955. <p id="isNaN">
  956. <b class="header">isNaN</b><code>_.isNaN(object)</code>
  957. <br />
  958. Returns <i>true</i> if <b>object</b> is <i>NaN</i>.<br /> Note: this is not
  959. the same as the native <b>isNaN</b> function, which will also return
  960. true if the variable is <i>undefined</i>.
  961. </p>
  962. <pre>
  963. _.isNaN(NaN);
  964. =&gt; true
  965. isNaN(undefined);
  966. =&gt; true
  967. _.isNaN(undefined);
  968. =&gt; false
  969. </pre>
  970. <p id="isNull">
  971. <b class="header">isNull</b><code>_.isNull(object)</code>
  972. <br />
  973. Returns <i>true</i> if the value of <b>object</b> is <i>null</i>.
  974. </p>
  975. <pre>
  976. _.isNull(null);
  977. =&gt; true
  978. _.isNull(undefined);
  979. =&gt; false
  980. </pre>
  981. <p id="isUndefined">
  982. <b class="header">isUndefined</b><code>_.isUndefined(variable)</code>
  983. <br />
  984. Returns <i>true</i> if <b>variable</b> is <i>undefined</i>.
  985. </p>
  986. <pre>
  987. _.isUndefined(window.missingVariable);
  988. =&gt; true
  989. </pre>
  990. <h2>Utility Functions</h2>
  991. <p id="noConflict">
  992. <b class="header">noConflict</b><code>_.noConflict()</code>
  993. <br />
  994. Give control of the "_" variable back to its previous owner. Returns
  995. a reference to the <b>Underscore</b> object.
  996. </p>
  997. <pre>
  998. var underscore = _.noConflict();</pre>
  999. <p id="identity">
  1000. <b class="header">identity</b><code>_.identity(value)</code>
  1001. <br />
  1002. Returns the same value that is used as the argument. In math:
  1003. <tt>f(x) = x</tt><br />
  1004. This function looks useless, but is used throughout Underscore as
  1005. a default iterator.
  1006. </p>
  1007. <pre>
  1008. var moe = {name : 'moe'};
  1009. moe === _.identity(moe);
  1010. =&gt; true</pre>
  1011. <p id="times">
  1012. <b class="header">times</b><code>_.times(n, iterator)</code>
  1013. <br />
  1014. Invokes the given iterator function <b>n</b> times.
  1015. </p>
  1016. <pre>
  1017. _(3).times(function(){ genie.grantWish(); });</pre>
  1018. <p id="mixin">
  1019. <b class="header">mixin</b><code>_.mixin(object)</code>
  1020. <br />
  1021. Allows you to extend Underscore with your own utility functions. Pass
  1022. a hash of <tt>{name: function}</tt> definitions to have your functions
  1023. added to the Underscore object, as well as the OOP wrapper.
  1024. </p>
  1025. <pre>
  1026. _.mixin({
  1027. capitalize : function(string) {
  1028. return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  1029. }
  1030. });
  1031. _("fabio").capitalize();
  1032. =&gt; "Fabio"
  1033. </pre>
  1034. <p id="uniqueId">
  1035. <b class="header">uniqueId</b><code>_.uniqueId([prefix])</code>
  1036. <br />
  1037. Generate a globally-unique id for client-side models or DOM elements
  1038. that need one. If <b>prefix</b> is passed, the id will be appended to it.
  1039. </p>
  1040. <pre>
  1041. _.uniqueId('contact_');
  1042. =&gt; 'contact_104'</pre>
  1043. <p id="template">
  1044. <b class="header">template</b><code>_.template(templateString, [context])</code>
  1045. <br />
  1046. Compiles JavaScript templates into functions that can be evaluated
  1047. for rendering. Useful for rendering complicated bits of HTML from JSON
  1048. data sources. Template functions can both interpolate variables, using<br />
  1049. <tt>&lt;%= &hellip; %&gt;</tt>, as well as execute arbitrary JavaScript code, with
  1050. <tt>&lt;% &hellip; %&gt;</tt>. When you evaluate a template function, pass in a
  1051. <b>context</b> object that has properties corresponding to the template's free
  1052. variables. If you're writing a one-off, you can pass the <b>context</b>
  1053. object as the second parameter to <b>template</b> in order to render
  1054. immediately instead of returning a template function.
  1055. </p>
  1056. <pre>
  1057. var compiled = _.template("hello: &lt;%= name %&gt;");
  1058. compiled({name : 'moe'});
  1059. =&gt; "hello: moe"
  1060. var list = "&lt;% _.each(people, function(name) { %&gt; &lt;li&gt;&lt;%= name %&gt;&lt;/li&gt; &lt;% }); %&gt;";
  1061. _.template(list, {people : ['moe', 'curly', 'larry']});
  1062. =&gt; "&lt;li&gt;moe&lt;/li&gt;&lt;li&gt;curly&lt;/li&gt;&lt;li&gt;larry&lt;/li&gt;"</pre>
  1063. <p>
  1064. You can also use <tt>print</tt> from within JavaScript code. This is
  1065. sometimes more convenient than using <tt>&lt;%= ... %&gt;</tt>.
  1066. </p>
  1067. <pre>
  1068. var compiled = _.template("&lt;% print('Hello ' + epithet); %&gt;");
  1069. compiled({epithet: "stooge"});
  1070. =&gt; "Hello stooge."</pre>
  1071. <p>
  1072. If ERB-style delimiters aren't your cup of tea, you can change Underscore's
  1073. template settings to use different symbols to set off interpolated code.
  1074. Define an <b>interpolate</b> regex, and an (optional) <b>evaluate</b> regex
  1075. to match expressions that should be inserted and evaluated, respectively.
  1076. If no <b>evaluate</b> regex is provided, your templates will only be
  1077. capable of interpolating values.
  1078. For example, to perform
  1079. <a href="http://github.com/janl/mustache.js#readme">Mustache.js</a>
  1080. style templating:
  1081. </p>
  1082. <pre>
  1083. _.templateSettings = {
  1084. interpolate : /\{\{(.+?)\}\}/g
  1085. };
  1086. var template = _.template("Hello {{ name }}!");
  1087. template({name : "Mustache"});
  1088. =&gt; "Hello Mustache!"</pre>
  1089. <h2>Chaining</h2>
  1090. <p id="chain">
  1091. <b class="header">chain</b><code>_(obj).chain()</code>
  1092. <br />
  1093. Returns a wrapped object. Calling methods on this object will continue
  1094. to return wrapped objects until <tt>value</tt> is used. (
  1095. <a href="#styles">A more realistic example.</a>)
  1096. </p>
  1097. <pre>
  1098. var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
  1099. var youngest = _(stooges).chain()
  1100. .sortBy(function(stooge){ return stooge.age; })
  1101. .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  1102. .first()
  1103. .value();
  1104. =&gt; "moe is 21"
  1105. </pre>
  1106. <p id="value">
  1107. <b class="header">value</b><code>_(obj).value()</code>
  1108. <br />
  1109. Extracts the value of a wrapped object.
  1110. </p>
  1111. <pre>
  1112. _([1, 2, 3]).value();
  1113. =&gt; [1, 2, 3]
  1114. </pre>
  1115. <h2 id="duck_typing">Duck Typing</h2>
  1116. <p>
  1117. The <b>isType</b> (<tt>isArray</tt>, <tt>isFunction</tt>, <tt>isString</tt> ...) family of type-checking
  1118. functions use property detection to do their work, which, although
  1119. orders of magnitude faster than the alternative, isn't entirely safe when dealing
  1120. with objects that are used as hashes, where arbitrary strings are being
  1121. set for the keys. It's entirely possible for an object to masquerade as
  1122. another type, if you're setting properties with names like "concat" and
  1123. "charCodeAt". So be aware.
  1124. </p>
  1125. <p>
  1126. In a similar fashion, <tt>_.each</tt> and all of the other functions
  1127. based on it are designed to be able to iterate over any Array-like
  1128. JavaScript object, including <tt>arguments</tt>, NodeLists, and more.
  1129. Passing hash-like objects with a numeric <tt>length</tt> key won't work.
  1130. </p>
  1131. <h2>Links &amp; Suggested Reading</h2>
  1132. <p>
  1133. <a href="http://mirven.github.com/underscore.lua/">Underscore.lua</a>,
  1134. a Lua port of the functions that are applicable in both languages.
  1135. Includes OOP-wrapping and chaining.
  1136. The <a href="http://github.com/mirven/underscore.lua">source</a> is
  1137. available on GitHub.
  1138. </p>
  1139. <p>
  1140. <a href="http://brianhaveri.github.com/Underscore.php/">Underscore.php</a>,
  1141. a PHP port of the functions that are applicable in both languages.
  1142. Includes OOP-wrapping and chaining.
  1143. The <a href="http://github.com/brianhaveri/Underscore.php">source</a> is
  1144. available on GitHub.
  1145. </p>
  1146. <p>
  1147. <a href="http://vti.github.com/underscore-perl/">Underscore-perl</a>,
  1148. a Perl port of many of the Underscore.js functions,
  1149. aimed at on Perl hashes and arrays, also
  1150. <a href="https://github.com/vti/underscore-perl/">available on GitHub</a>.
  1151. </p>
  1152. <p>
  1153. <a href="https://github.com/edtsech/underscore.string">Underscore.string</a>,
  1154. an Underscore extension that adds functions for string-manipulation:
  1155. <tt>trim</tt>, <tt>startsWith</tt>, <tt>contains</tt>, <tt>capitalize</tt>,
  1156. <tt>reverse</tt>, <tt>sprintf</tt>, and more.
  1157. </p>
  1158. <p>
  1159. Ruby's <a href="http://ruby-doc.org/core/classes/Enumerable.html">Enumerable</a> module.
  1160. </p>
  1161. <p>
  1162. <a href="http://www.prototypejs.org/">Prototype.js</a>, which provides
  1163. JavaScript with collection functions in the manner closest to Ruby's Enumerable.
  1164. </p>
  1165. <p>
  1166. Oliver Steele's
  1167. <a href="http://osteele.com/sources/javascript/functional/">Functional JavaScript</a>,
  1168. which includes comprehensive higher-order function support as well as string lambdas.
  1169. </p>
  1170. <p>
  1171. Michael Aufreiter's <a href="http://substance.io/#michael/data-js">Data.js</a>,
  1172. a data manipulation + persistence library for JavaScript.
  1173. </p>
  1174. <p>
  1175. Python's <a href="http://docs.python.org/library/itertools.html">itertools</a>.
  1176. </p>
  1177. <h2 id="changelog">Change Log</h2>
  1178. <p>
  1179. <b class="header">1.1.7</b> &mdash; <small><i>July 13, 2011</i></small><br />
  1180. Added <tt>_.groupBy</tt>, which aggregates a collection into groups of like items.
  1181. Added <tt>_.union</tt> and <tt>_.difference</tt>, to complement the
  1182. (re-named) <tt>_.intersection</tt>.
  1183. Various improvements for support of sparse arrays.
  1184. <tt>_.toArray</tt> now returns a clone, if directly passed an array.
  1185. <tt>_.functions</tt> now also returns the names of functions that are present
  1186. in the prototype chain.
  1187. </p>
  1188. <p>
  1189. <b class="header">1.1.6</b> &mdash; <small><i>April 18, 2011</i></small><br />
  1190. Added <tt>_.after</tt>, which will return a function that only runs after
  1191. first being called a specified number of times.
  1192. <tt>_.invoke</tt> can now take a direct function reference.
  1193. <tt>_.every</tt> now requires an iterator function to be passed, which
  1194. mirrors the ECMA5 API.
  1195. <tt>_.extend</tt> no longer copies keys when the value is undefined.
  1196. <tt>_.bind</tt> now errors when trying to bind an undefined value.
  1197. </p>
  1198. <p>
  1199. <b class="header">1.1.5</b> &mdash; <small><i>Mar 20, 2011</i></small><br />
  1200. Added an <tt>_.defaults</tt> function, for use merging together JS objects
  1201. representing default options.
  1202. Added an <tt>_.once</tt> function, for manufacturing functions that should
  1203. only ever execute a single time.
  1204. <tt>_.bind</tt> now delegates to the native ECMAScript 5 version,
  1205. where available.
  1206. <tt>_.keys</tt> now throws an error when used on non-Object values, as in
  1207. ECMAScript 5.
  1208. Fixed a bug with <tt>_.keys</tt> when used over sparse arrays.
  1209. </p>
  1210. <p>
  1211. <b class="header">1.1.4</b> &mdash; <small><i>Jan 9, 2011</i></small><br />
  1212. Improved compliance with ES5's Array methods when passing <tt>null</tt>
  1213. as a value. <tt>_.wrap</tt> now correctly sets <tt>this</tt> for the
  1214. wrapped function. <tt>_.indexOf</tt> now takes an optional flag for
  1215. finding the insertion index in an array that is guaranteed to already
  1216. be sorted. Avoiding the use of <tt>.callee</tt>, to allow <tt>_.isArray</tt>
  1217. to work properly in ES5's strict mode.
  1218. </p>
  1219. <p>
  1220. <b class="header">1.1.3</b> &mdash; <small><i>Dec 1, 2010</i></small><br />
  1221. In CommonJS, Underscore may now be required with just: <br />
  1222. <tt>var _ = require("underscore")</tt>.
  1223. Added <tt>_.throttle</tt> and <tt>_.debounce</tt> functions.
  1224. Removed <tt>_.breakLoop</tt>, in favor of an ECMA5-style un-<i>break</i>-able
  1225. each implementation &mdash; this removes the try/catch, and you'll now have
  1226. better stack traces for exceptions that are thrown within an Underscore iterator.
  1227. Improved the <b>isType</b> family of functions for better interoperability
  1228. with Internet Explorer host objects.
  1229. <tt>_.template</tt> now correctly escapes backslashes in templates.
  1230. Improved <tt>_.reduce</tt> compatibility with the ECMA5 version:
  1231. if you don't pass an initial value, the first item in the collection is used.
  1232. <tt>_.each</tt> no longer returns the iterated collection, for improved
  1233. consistency with ES5's <tt>forEach</tt>.
  1234. </p>
  1235. <p>
  1236. <b class="header">1.1.2</b><br />
  1237. Fixed <tt>_.contains</tt>, which was mistakenly pointing at
  1238. <tt>_.intersect</tt> instead of <tt>_.include</tt>, like it should
  1239. have been. Added <tt>_.unique</tt> as an alias for <tt>_.uniq</tt>.
  1240. </p>
  1241. <p>
  1242. <b class="header">1.1.1</b><br />
  1243. Improved the speed of <tt>_.template</tt>, and its handling of multiline
  1244. interpolations. Ryan Tenney contributed optimizations to many Underscore
  1245. functions. An annotated version of the source code is now available.
  1246. </p>
  1247. <p>
  1248. <b class="header">1.1.0</b><br />
  1249. The method signature of <tt>_.reduce</tt> has been changed to match
  1250. the ECMAScript 5 signature, instead of the Ruby/Prototype.js version.
  1251. This is a backwards-incompatible change. <tt>_.template</tt> may now be
  1252. called with no arguments, and preserves whitespace. <tt>_.contains</tt>
  1253. is a new alias for <tt>_.include</tt>.
  1254. </p>
  1255. <p>
  1256. <b class="header">1.0.4</b><br />
  1257. <a href="http://themoell.com/">Andri Möll</a> contributed the <tt>_.memoize</tt>
  1258. function, which can be used to speed up expensive repeated computations
  1259. by caching the results.
  1260. </p>
  1261. <p>
  1262. <b class="header">1.0.3</b><br />
  1263. Patch that makes <tt>_.isEqual</tt> return <tt>false</tt> if any property
  1264. of the compared object has a <tt>NaN</tt> value. Technically the correct
  1265. thing to do, but of questionable semantics. Watch out for NaN comparisons.
  1266. </p>
  1267. <p>
  1268. <b class="header">1.0.2</b><br />
  1269. Fixes <tt>_.isArguments</tt> in recent versions of Opera, which have
  1270. arguments objects as real Arrays.
  1271. </p>
  1272. <p>
  1273. <b class="header">1.0.1</b><br />
  1274. Bugfix for <tt>_.isEqual</tt>, when comparing two objects with the same
  1275. number of undefined keys, but with different names.
  1276. </p>
  1277. <p>
  1278. <b class="header">1.0.0</b><br />
  1279. Things have been stable for many months now, so Underscore is now
  1280. considered to be out of beta, at <b>1.0</b>. Improvements since <b>0.6</b>
  1281. include <tt>_.isBoolean</tt>, and the ability to have <tt>_.extend</tt>
  1282. take multiple source objects.
  1283. </p>
  1284. <p>
  1285. <b class="header">0.6.0</b><br />
  1286. Major release. Incorporates a number of
  1287. <a href="http://github.com/ratbeard">Mile Frawley's</a> refactors for
  1288. safer duck-typing on collection functions, and cleaner internals. A new
  1289. <tt>_.mixin</tt> method that allows you to extend Underscore with utility
  1290. functions of your own. Added <tt>_.times</tt>, which works the same as in
  1291. Ruby or Prototype.js. Native support for ECMAScript 5's <tt>Array.isArray</tt>,
  1292. and <tt>Object.keys</tt>.
  1293. </p>
  1294. <p>
  1295. <b class="header">0.5.8</b><br />
  1296. Fixed Underscore's collection functions to work on
  1297. <a href="https://developer.mozilla.org/En/DOM/NodeList">NodeLists</a> and
  1298. <a href="https://developer.mozilla.org/En/DOM/HTMLCollection">HTMLCollections</a>
  1299. once more, thanks to
  1300. <a href="http://github.com/jmtulloss">Justin Tulloss</a>.
  1301. </p>
  1302. <p>
  1303. <b class="header">0.5.7</b><br />
  1304. A safer implementation of <tt>_.isArguments</tt>, and a
  1305. faster <tt>_.isNumber</tt>,<br />thanks to
  1306. <a href="http://jedschmidt.com/">Jed Schmidt</a>.
  1307. </p>
  1308. <p>
  1309. <b class="header">0.5.6</b><br />
  1310. Customizable delimiters for <tt>_.template</tt>, contributed by
  1311. <a href="http://github.com/iamnoah">Noah Sloan</a>.
  1312. </p>
  1313. <p>
  1314. <b class="header">0.5.5</b><br />
  1315. Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object.
  1316. </p>
  1317. <p>
  1318. <b class="header">0.5.4</b><br />
  1319. Fix for multiple single quotes within a template string for
  1320. <tt>_.template</tt>. See:
  1321. <a href="http://www.west-wind.com/Weblog/posts/509108.aspx">Rick Strahl's blog post</a>.
  1322. </p>
  1323. <p>
  1324. <b class="header">0.5.2</b><br />
  1325. New implementations of <tt>isArray</tt>, <tt>isDate</tt>, <tt>isFunction</tt>,
  1326. <tt>isNumber</tt>, <tt>isRegExp</tt>, and <tt>isString</tt>, thanks to
  1327. a suggestion from
  1328. <a href="http://www.broofa.com/">Robert Kieffer</a>.
  1329. Instead of doing <tt>Object#toString</tt>
  1330. comparisons, they now check for expected properties, which is less safe,
  1331. but more than an order of magnitude faster. Most other Underscore
  1332. functions saw minor speed improvements as a result.
  1333. <a href="http://dolzhenko.org/">Evgeniy Dolzhenko</a>
  1334. contributed <tt>_.tap</tt>,
  1335. <a href="http://ruby-doc.org/core-1.9/classes/Object.html#M000191">similar to Ruby 1.9's</a>,
  1336. which is handy for injecting side effects (like logging) into chained calls.
  1337. </p>
  1338. <p>
  1339. <b class="header">0.5.1</b><br />
  1340. Added an <tt>_.isArguments</tt> function. Lots of little safety checks
  1341. and optimizations contributed by
  1342. <a href="http://github.com/iamnoah/">Noah Sloan</a> and
  1343. <a href="http://themoell.com/">Andri Möll</a>.
  1344. </p>
  1345. <p>
  1346. <b class="header">0.5.0</b><br />
  1347. <b>[API Changes]</b> <tt>_.bindAll</tt> now takes the context object as
  1348. its first parameter. If no method names are passed, all of the context
  1349. object's methods are bound to it, enabling chaining and easier binding.
  1350. <tt>_.functions</tt> now takes a single argument and returns the names
  1351. of its Function properties. Calling <tt>_.functions(_)</tt> will get you
  1352. the previous behavior.
  1353. Added <tt>_.isRegExp</tt> so that <tt>isEqual</tt> can now test for RegExp equality.
  1354. All of the "is" functions have been shrunk down into a single definition.
  1355. <a href="http://github.com/grayrest/">Karl Guertin</a> contributed patches.
  1356. </p>
  1357. <p>
  1358. <b class="header">0.4.7</b><br />
  1359. Added <tt>isDate</tt>, <tt>isNaN</tt>, and <tt>isNull</tt>, for completeness.
  1360. Optimizations for <tt>isEqual</tt> when checking equality between Arrays
  1361. or Dates. <tt>_.keys</tt> is now <small><i><b>25%&ndash;2X</b></i></small> faster (depending on your
  1362. browser) which speeds up the functions that rely on it, such as <tt>_.each</tt>.
  1363. </p>
  1364. <p>
  1365. <b class="header">0.4.6</b><br />
  1366. Added the <tt>range</tt> function, a port of the
  1367. <a href="http://docs.python.org/library/functions.html#range">Python
  1368. function of the same name</a>, for generating flexibly-numbered lists
  1369. of integers. Original patch contributed by
  1370. <a href="http://github.com/kylichuku">Kirill Ishanov</a>.
  1371. </p>
  1372. <p>
  1373. <b class="header">0.4.5</b><br />
  1374. Added <tt>rest</tt> for Arrays and arguments objects, and aliased
  1375. <tt>first</tt> as <tt>head</tt>, and <tt>rest</tt> as <tt>tail</tt>,
  1376. thanks to <a href="http://github.com/lukesutton/">Luke Sutton</a>'s patches.
  1377. Added tests ensuring that all Underscore Array functions also work on
  1378. <i>arguments</i> objects.
  1379. </p>
  1380. <p>
  1381. <b class="header">0.4.4</b><br />
  1382. Added <tt>isString</tt>, and <tt>isNumber</tt>, for consistency. Fixed
  1383. <tt>_.isEqual(NaN, NaN)</tt> to return <i>true</i> (which is debatable).
  1384. </p>
  1385. <p>
  1386. <b class="header">0.4.3</b><br />
  1387. Started using the native <tt>StopIteration</tt> object in browsers that support it.
  1388. Fixed Underscore setup for CommonJS environments.
  1389. </p>
  1390. <p>
  1391. <b class="header">0.4.2</b><br />
  1392. Renamed the unwrapping function to <tt>value</tt>, for clarity.
  1393. </p>
  1394. <p>
  1395. <b class="header">0.4.1</b><br />
  1396. Chained Underscore objects now support the Array prototype methods, so
  1397. that you can perform the full range of operations on a wrapped array
  1398. without having to break your chain. Added a <tt>breakLoop</tt> method
  1399. to <b>break</b> in the middle of any Underscore iteration. Added an
  1400. <tt>isEmpty</tt> function that works on arrays and objects.
  1401. </p>
  1402. <p>
  1403. <b class="header">0.4.0</b><br />
  1404. All Underscore functions can now be called in an object-oriented style,
  1405. like so: <tt>_([1, 2, 3]).map(...);</tt>. Original patch provided by
  1406. <a href="http://macournoyer.com/">Marc-André Cournoyer</a>.
  1407. Wrapped objects can be chained through multiple
  1408. method invocations. A <a href="#functions"><tt>functions</tt></a> method
  1409. was added, providing a sorted list of all the functions in Underscore.
  1410. </p>
  1411. <p>
  1412. <b class="header">0.3.3</b><br />
  1413. Added the JavaScript 1.8 function <tt>reduceRight</tt>. Aliased it
  1414. as <tt>foldr</tt>, and aliased <tt>reduce</tt> as <tt>foldl</tt>.
  1415. </p>
  1416. <p>
  1417. <b class="header">0.3.2</b><br />
  1418. Now runs on stock <a href="http://www.mozilla.org/rhino/">Rhino</a>
  1419. interpreters with: <tt>load("underscore.js")</tt>.
  1420. Added <a href="#identity"><tt>identity</tt></a> as a utility function.
  1421. </p>
  1422. <p>
  1423. <b class="header">0.3.1</b><br />
  1424. All iterators are now passed in the original collection as their third
  1425. argument, the same as JavaScript 1.6's <b>forEach</b>. Iterating over
  1426. objects is now called with <tt>(value, key, collection)</tt>, for details
  1427. see <a href="#each"><tt>_.each</tt></a>.
  1428. </p>
  1429. <p>
  1430. <b class="header">0.3.0</b><br />
  1431. Added <a href="http://github.com/dmitryBaranovskiy">Dmitry Baranovskiy</a>'s
  1432. comprehensive optimizations, merged in
  1433. <a href="http://github.com/kriskowal/">Kris Kowal</a>'s patches to make Underscore
  1434. <a href="http://wiki.commonjs.org/wiki/CommonJS">CommonJS</a> and
  1435. <a href="http://narwhaljs.org/">Narwhal</a> compliant.
  1436. </p>
  1437. <p>
  1438. <b class="header">0.2.0</b><br />
  1439. Added <tt>compose</tt> and <tt>lastIndexOf</tt>, renamed <tt>inject</tt> to
  1440. <tt>reduce</tt>, added aliases for <tt>inject</tt>, <tt>filter</tt>,
  1441. <tt>every</tt>, <tt>some</tt>, and <tt>forEach</tt>.
  1442. </p>
  1443. <p>
  1444. <b class="header">0.1.1</b><br />
  1445. Added <tt>noConflict</tt>, so that the "Underscore" object can be assigned to
  1446. other variables.
  1447. </p>
  1448. <p>
  1449. <b class="header">0.1.0</b><br />
  1450. Initial release of Underscore.js.
  1451. </p>
  1452. <p>
  1453. <a href="http://documentcloud.org/" title="A DocumentCloud Project" style="background:none;">
  1454. <img src="http://jashkenas.s3.amazonaws.com/images/a_documentcloud_project.png" alt="A DocumentCloud Project" />
  1455. </a>
  1456. </p>
  1457. </div>
  1458. </div>
  1459. <!-- Include Underscore, so you can play with it in the console. -->
  1460. <script type="text/javascript" src="underscore.js"></script>
  1461. </body>
  1462. </html>