PageRenderTime 69ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/node_modules/grunt-jasmine-task/node_modules/grunt/node_modules/underscore/index.html

http://github.com/creynders/jsfsa
HTML | 1816 lines | 1652 code | 164 blank | 0 comment | 0 complexity | d4081c76f5bcea311dd027f47b2c5179 MD5 | raw file
Possible License(s): MIT, Apache-2.0, GPL-2.0

Large files files are truncated, but you can click here to view the full 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: 14px;
  10. line-height: 22px;
  11. background: #f4f4f4 url(docs/images/background.png);
  12. color: #000;
  13. font-family: Helvetica Neue, Helvetica, Arial;
  14. }
  15. .interface {
  16. font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
  17. }
  18. div#sidebar {
  19. background: #fff;
  20. position: fixed;
  21. top: 0; left: 0; bottom: 0;
  22. width: 200px;
  23. overflow-y: auto;
  24. overflow-x: hidden;
  25. padding: 15px 0 30px 30px;
  26. border-right: 1px solid #bbb;
  27. box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
  28. }
  29. a.toc_title, a.toc_title:visited {
  30. display: block;
  31. color: black;
  32. font-weight: bold;
  33. margin-top: 15px;
  34. }
  35. a.toc_title:hover {
  36. text-decoration: underline;
  37. }
  38. #sidebar .version {
  39. font-size: 10px;
  40. font-weight: normal;
  41. }
  42. ul.toc_section {
  43. font-size: 11px;
  44. line-height: 14px;
  45. margin: 5px 0 0 0;
  46. padding-left: 0px;
  47. list-style-type: none;
  48. font-family: Lucida Grande;
  49. }
  50. .toc_section li {
  51. cursor: pointer;
  52. margin: 0 0 3px 0;
  53. }
  54. .toc_section li a {
  55. text-decoration: none;
  56. color: black;
  57. }
  58. .toc_section li a:hover {
  59. text-decoration: underline;
  60. }
  61. div.container {
  62. width: 550px;
  63. margin: 40px 0 50px 260px;
  64. }
  65. p {
  66. margin: 20px 0;
  67. width: 550px;
  68. }
  69. a, a:visited {
  70. color: #444;
  71. }
  72. a:active, a:hover {
  73. color: #000;
  74. }
  75. h1, h2, h3, h4, h5, h6 {
  76. padding-top: 20px;
  77. }
  78. h2 {
  79. font-size: 20px;
  80. }
  81. b.header {
  82. font-size: 16px;
  83. line-height: 30px;
  84. }
  85. span.alias {
  86. font-size: 14px;
  87. font-style: italic;
  88. margin-left: 20px;
  89. }
  90. table, tr, td {
  91. margin: 0; padding: 0;
  92. }
  93. td {
  94. padding: 2px 12px 2px 0;
  95. }
  96. ul {
  97. list-style-type: circle;
  98. padding: 0 0 0 20px;
  99. }
  100. li {
  101. width: 500px;
  102. margin-bottom: 10px;
  103. }
  104. code, pre, tt {
  105. font-family: Monaco, Consolas, "Lucida Console", monospace;
  106. font-size: 12px;
  107. line-height: 18px;
  108. font-style: normal;
  109. }
  110. tt {
  111. padding: 0px 3px;
  112. background: #fff;
  113. border: 1px solid #ddd;
  114. zoom: 1;
  115. }
  116. code {
  117. margin-left: 20px;
  118. }
  119. pre {
  120. font-size: 12px;
  121. padding: 2px 0 2px 15px;
  122. border-left: 5px solid #bbb;
  123. margin: 0px 0 30px;
  124. }
  125. </style>
  126. </head>
  127. <body>
  128. <div id="sidebar" class="interface">
  129. <a class="toc_title" href="#">
  130. Underscore.js <span class="version">(1.2.4)</span>
  131. </a>
  132. <a class="toc_title" href="#">
  133. Introduction
  134. </a>
  135. <a class="toc_title" href="#collections">
  136. Collections
  137. </a>
  138. <ul class="toc_section">
  139. <li>- <a href="#each">each</a></li>
  140. <li>- <a href="#map">map</a></li>
  141. <li>- <a href="#reduce">reduce</a></li>
  142. <li>- <a href="#reduceRight">reduceRight</a></li>
  143. <li>- <a href="#find">find</a></li>
  144. <li>- <a href="#filter">filter</a></li>
  145. <li>- <a href="#reject">reject</a></li>
  146. <li>- <a href="#all">all</a></li>
  147. <li>- <a href="#any">any</a></li>
  148. <li>- <a href="#include">include</a></li>
  149. <li>- <a href="#invoke">invoke</a></li>
  150. <li>- <a href="#pluck">pluck</a></li>
  151. <li>- <a href="#max">max</a></li>
  152. <li>- <a href="#min">min</a></li>
  153. <li>- <a href="#sortBy">sortBy</a></li>
  154. <li>- <a href="#groupBy">groupBy</a></li>
  155. <li>- <a href="#sortedIndex">sortedIndex</a></li>
  156. <li>- <a href="#shuffle">shuffle</a></li>
  157. <li>- <a href="#toArray">toArray</a></li>
  158. <li>- <a href="#size">size</a></li>
  159. </ul>
  160. <a class="toc_title" href="#arrays">
  161. Arrays
  162. </a>
  163. <ul class="toc_section">
  164. <li>- <a href="#first">first</a></li>
  165. <li>- <a href="#initial">initial</a></li>
  166. <li>- <a href="#last">last</a></li>
  167. <li>- <a href="#rest">rest</a></li>
  168. <li>- <a href="#compact">compact</a></li>
  169. <li>- <a href="#flatten">flatten</a></li>
  170. <li>- <a href="#without">without</a></li>
  171. <li>- <a href="#union">union</a></li>
  172. <li>- <a href="#intersection">intersection</a></li>
  173. <li>- <a href="#difference">difference</a></li>
  174. <li>- <a href="#uniq">uniq</a></li>
  175. <li>- <a href="#zip">zip</a></li>
  176. <li>- <a href="#indexOf">indexOf</a></li>
  177. <li>- <a href="#lastIndexOf">lastIndexOf</a></li>
  178. <li>- <a href="#range">range</a></li>
  179. </ul>
  180. <a class="toc_title" href="#functions">
  181. Functions
  182. </a>
  183. <ul class="toc_section">
  184. <li>- <a href="#bind">bind</a></li>
  185. <li>- <a href="#bindAll">bindAll</a></li>
  186. <li>- <a href="#memoize">memoize</a></li>
  187. <li>- <a href="#delay">delay</a></li>
  188. <li>- <a href="#defer">defer</a></li>
  189. <li>- <a href="#throttle">throttle</a></li>
  190. <li>- <a href="#debounce">debounce</a></li>
  191. <li>- <a href="#once">once</a></li>
  192. <li>- <a href="#after">after</a></li>
  193. <li>- <a href="#wrap">wrap</a></li>
  194. <li>- <a href="#compose">compose</a></li>
  195. </ul>
  196. <a class="toc_title" href="#objects">
  197. Objects
  198. </a>
  199. <ul class="toc_section">
  200. <li>- <a href="#keys">keys</a></li>
  201. <li>- <a href="#values">values</a></li>
  202. <li>- <a href="#functions">functions</a></li>
  203. <li>- <a href="#extend">extend</a></li>
  204. <li>- <a href="#defaults">defaults</a></li>
  205. <li>- <a href="#clone">clone</a></li>
  206. <li>- <a href="#tap">tap</a></li>
  207. <li>- <a href="#isEqual">isEqual</a></li>
  208. <li>- <a href="#isEmpty">isEmpty</a></li>
  209. <li>- <a href="#isElement">isElement</a></li>
  210. <li>- <a href="#isArray">isArray</a></li>
  211. <li>- <a href="#isArguments">isArguments</a></li>
  212. <li>- <a href="#isFunction">isFunction</a></li>
  213. <li>- <a href="#isString">isString</a></li>
  214. <li>- <a href="#isNumber">isNumber</a></li>
  215. <li>- <a href="#isBoolean">isBoolean</a></li>
  216. <li>- <a href="#isDate">isDate</a></li>
  217. <li>- <a href="#isRegExp">isRegExp</a></li>
  218. <li>- <a href="#isNaN">isNaN</a></li>
  219. <li>- <a href="#isNull">isNull</a></li>
  220. <li>- <a href="#isUndefined">isUndefined</a></li>
  221. </ul>
  222. <a class="toc_title" href="#utility">
  223. Utility
  224. </a>
  225. <ul class="toc_section">
  226. <li>- <a href="#noConflict">noConflict</a></li>
  227. <li>- <a href="#identity">identity</a></li>
  228. <li>- <a href="#times">times</a></li>
  229. <li>- <a href="#mixin">mixin</a></li>
  230. <li>- <a href="#uniqueId">uniqueId</a></li>
  231. <li>- <a href="#escape">escape</a></li>
  232. <li>- <a href="#template">template</a></li>
  233. </ul>
  234. <a class="toc_title" href="#chaining">
  235. Chaining
  236. </a>
  237. <ul class="toc_section">
  238. <li>- <a href="#chain">chain</a></li>
  239. <li>- <a href="#value">value</a></li>
  240. </ul>
  241. <a class="toc_title" href="#links">
  242. Links
  243. </a>
  244. <a class="toc_title" href="#changelog">
  245. Change Log
  246. </a>
  247. </div>
  248. <div class="container">
  249. <p id="introduction">
  250. <img style="width: 396px; height: 69px;" src="docs/images/underscore.png" alt="Underscore.js" />
  251. </p>
  252. <p>
  253. <a href="http://github.com/documentcloud/underscore/">Underscore</a> is a
  254. utility-belt library for JavaScript that provides a lot of the
  255. functional programming support that you would expect in
  256. <a href="http://prototypejs.org/api">Prototype.js</a>
  257. (or <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">Ruby</a>),
  258. but without extending any of the built-in JavaScript objects. It's the
  259. tie to go along with <a href="http://docs.jquery.com">jQuery</a>'s tux,
  260. and <a href="http://backbonejs.org">Backbone.js</a>'s suspenders.
  261. </p>
  262. <p>
  263. Underscore provides 60-odd functions that support both the usual
  264. functional suspects: <b>map</b>, <b>select</b>, <b>invoke</b> &mdash;
  265. as well as more specialized helpers: function binding, javascript
  266. templating, deep equality testing, and so on. It delegates to built-in
  267. functions, if present, so modern browsers will use the
  268. native implementations of <b>forEach</b>, <b>map</b>, <b>reduce</b>,
  269. <b>filter</b>, <b>every</b>, <b>some</b> and <b>indexOf</b>.
  270. </p>
  271. <p>
  272. A complete <a href="test/test.html">Test &amp; Benchmark Suite</a>
  273. is included for your perusal.
  274. </p>
  275. <p>
  276. You may also read through the <a href="docs/underscore.html">annotated source code</a>.
  277. </p>
  278. <p>
  279. The project is
  280. <a href="http://github.com/documentcloud/underscore/">hosted on GitHub</a>.
  281. You can report bugs and discuss features on the
  282. <a href="http://github.com/documentcloud/underscore/issues">issues page</a>,
  283. on Freenode in the <tt>#documentcloud</tt> channel,
  284. or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
  285. </p>
  286. <p>
  287. <i>Underscore is an open-source component of <a href="http://documentcloud.org/">DocumentCloud</a>.</i>
  288. </p>
  289. <h2>Downloads <i style="padding-left: 12px; font-size:12px;">(Right-click, and use "Save As")</i></h2>
  290. <table>
  291. <tr>
  292. <td><a href="underscore.js">Development Version (1.2.4)</a></td>
  293. <td><i>34kb, Uncompressed with Comments</i></td>
  294. </tr>
  295. <tr>
  296. <td><a href="underscore-min.js">Production Version (1.2.4)</a></td>
  297. <td><i>&lt; 4kb, Minified and Gzipped</i></td>
  298. </tr>
  299. </table>
  300. <div id="documentation">
  301. <h2 id="collections">Collection Functions (Arrays or Objects)</h2>
  302. <p id="each">
  303. <b class="header">each</b><code>_.each(list, iterator, [context])</code>
  304. <span class="alias">Alias: <b>forEach</b></span>
  305. <br />
  306. Iterates over a <b>list</b> of elements, yielding each in turn to an <b>iterator</b>
  307. function. The <b>iterator</b> is bound to the <b>context</b> object, if one is
  308. passed. Each invocation of <b>iterator</b> is called with three arguments:
  309. <tt>(element, index, list)</tt>. If <b>list</b> is a JavaScript object, <b>iterator</b>'s
  310. arguments will be <tt>(value, key, list)</tt>. Delegates to the native
  311. <b>forEach</b> function if it exists.
  312. </p>
  313. <pre>
  314. _.each([1, 2, 3], function(num){ alert(num); });
  315. =&gt; alerts each number in turn...
  316. _.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); });
  317. =&gt; alerts each number in turn...</pre>
  318. <p id="map">
  319. <b class="header">map</b><code>_.map(list, iterator, [context])</code>
  320. <br />
  321. Produces a new array of values by mapping each value in <b>list</b>
  322. through a transformation function (<b>iterator</b>). If the native <b>map</b> method
  323. exists, it will be used instead. If <b>list</b> is a JavaScript object,
  324. <b>iterator</b>'s arguments will be <tt>(value, key, list)</tt>.
  325. </p>
  326. <pre>
  327. _.map([1, 2, 3], function(num){ return num * 3; });
  328. =&gt; [3, 6, 9]
  329. _.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; });
  330. =&gt; [3, 6, 9]</pre>
  331. <p id="reduce">
  332. <b class="header">reduce</b><code>_.reduce(list, iterator, memo, [context])</code>
  333. <span class="alias">Aliases: <b>inject, foldl</b></span>
  334. <br />
  335. Also known as <b>inject</b> and <b>foldl</b>, <b>reduce</b> boils down a
  336. <b>list</b> of values into a single value. <b>Memo</b> is the initial state
  337. of the reduction, and each successive step of it should be returned by
  338. <b>iterator</b>.
  339. </p>
  340. <pre>
  341. var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
  342. =&gt; 6
  343. </pre>
  344. <p id="reduceRight">
  345. <b class="header">reduceRight</b><code>_.reduceRight(list, iterator, memo, [context])</code>
  346. <span class="alias">Alias: <b>foldr</b></span>
  347. <br />
  348. The right-associative version of <b>reduce</b>. Delegates to the
  349. JavaScript 1.8 version of <b>reduceRight</b>, if it exists. <b>Foldr</b>
  350. is not as useful in JavaScript as it would be in a language with lazy
  351. evaluation.
  352. </p>
  353. <pre>
  354. var list = [[0, 1], [2, 3], [4, 5]];
  355. var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  356. =&gt; [4, 5, 2, 3, 0, 1]
  357. </pre>
  358. <p id="find">
  359. <b class="header">find</b><code>_.find(list, iterator, [context])</code>
  360. <span class="alias">Alias: <b>detect</b></span>
  361. <br />
  362. Looks through each value in the <b>list</b>, returning the first one that
  363. passes a truth test (<b>iterator</b>). The function returns as
  364. soon as it finds an acceptable element, and doesn't traverse the
  365. entire list.
  366. </p>
  367. <pre>
  368. var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  369. =&gt; 2
  370. </pre>
  371. <p id="filter">
  372. <b class="header">filter</b><code>_.filter(list, iterator, [context])</code>
  373. <span class="alias">Alias: <b>select</b></span>
  374. <br />
  375. Looks through each value in the <b>list</b>, returning an array of all
  376. the values that pass a truth test (<b>iterator</b>). Delegates to the
  377. native <b>filter</b> method, if it exists.
  378. </p>
  379. <pre>
  380. var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  381. =&gt; [2, 4, 6]
  382. </pre>
  383. <p id="reject">
  384. <b class="header">reject</b><code>_.reject(list, iterator, [context])</code>
  385. <br />
  386. Returns the values in <b>list</b> without the elements that the truth
  387. test (<b>iterator</b>) passes. The opposite of <b>filter</b>.
  388. </p>
  389. <pre>
  390. var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  391. =&gt; [1, 3, 5]
  392. </pre>
  393. <p id="all">
  394. <b class="header">all</b><code>_.all(list, iterator, [context])</code>
  395. <span class="alias">Alias: <b>every</b></span>
  396. <br />
  397. Returns <i>true</i> if all of the values in the <b>list</b> pass the <b>iterator</b>
  398. truth test. Delegates to the native method <b>every</b>, if present.
  399. </p>
  400. <pre>
  401. _.all([true, 1, null, 'yes'], _.identity);
  402. =&gt; false
  403. </pre>
  404. <p id="any">
  405. <b class="header">any</b><code>_.any(list, [iterator], [context])</code>
  406. <span class="alias">Alias: <b>some</b></span>
  407. <br />
  408. Returns <i>true</i> if any of the values in the <b>list</b> pass the
  409. <b>iterator</b> truth test. Short-circuits and stops traversing the list
  410. if a true element is found. Delegates to the native method <b>some</b>,
  411. if present.
  412. </p>
  413. <pre>
  414. _.any([null, 0, 'yes', false]);
  415. =&gt; true
  416. </pre>
  417. <p id="include">
  418. <b class="header">include</b><code>_.include(list, value)</code>
  419. <span class="alias">Alias: <b>contains</b></span>
  420. <br />
  421. Returns <i>true</i> if the <b>value</b> is present in the <b>list</b>, using
  422. <i>===</i> to test equality. Uses <b>indexOf</b> internally, if <b>list</b>
  423. is an Array.
  424. </p>
  425. <pre>
  426. _.include([1, 2, 3], 3);
  427. =&gt; true
  428. </pre>
  429. <p id="invoke">
  430. <b class="header">invoke</b><code>_.invoke(list, methodName, [*arguments])</code>
  431. <br />
  432. Calls the method named by <b>methodName</b> on each value in the <b>list</b>.
  433. Any extra arguments passed to <b>invoke</b> will be forwarded on to the
  434. method invocation.
  435. </p>
  436. <pre>
  437. _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  438. =&gt; [[1, 5, 7], [1, 2, 3]]
  439. </pre>
  440. <p id="pluck">
  441. <b class="header">pluck</b><code>_.pluck(list, propertyName)</code>
  442. <br />
  443. A convenient version of what is perhaps the most common use-case for
  444. <b>map</b>: extracting a list of property values.
  445. </p>
  446. <pre>
  447. var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
  448. _.pluck(stooges, 'name');
  449. =&gt; ["moe", "larry", "curly"]
  450. </pre>
  451. <p id="max">
  452. <b class="header">max</b><code>_.max(list, [iterator], [context])</code>
  453. <br />
  454. Returns the maximum value in <b>list</b>. If <b>iterator</b> is passed,
  455. it will be used on each value to generate the criterion by which the
  456. value is ranked.
  457. </p>
  458. <pre>
  459. var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
  460. _.max(stooges, function(stooge){ return stooge.age; });
  461. =&gt; {name : 'curly', age : 60};
  462. </pre>
  463. <p id="min">
  464. <b class="header">min</b><code>_.min(list, [iterator], [context])</code>
  465. <br />
  466. Returns the minimum value in <b>list</b>. If <b>iterator</b> is passed,
  467. it will be used on each value to generate the criterion by which the
  468. value is ranked.
  469. </p>
  470. <pre>
  471. var numbers = [10, 5, 100, 2, 1000];
  472. _.min(numbers);
  473. =&gt; 2
  474. </pre>
  475. <p id="sortBy">
  476. <b class="header">sortBy</b><code>_.sortBy(list, iterator, [context])</code>
  477. <br />
  478. Returns a sorted copy of <b>list</b>, ranked by the results of running
  479. each value through <b>iterator</b>.
  480. </p>
  481. <pre>
  482. _.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
  483. =&gt; [5, 4, 6, 3, 1, 2]
  484. </pre>
  485. <p id="groupBy">
  486. <b class="header">groupBy</b><code>_.groupBy(list, iterator)</code>
  487. <br />
  488. Splits a collection into sets, grouped by the result of running each
  489. value through <b>iterator</b>. If <b>iterator</b> is a string instead of
  490. a function, groups by the property named by <b>iterator</b> on each of
  491. the values.
  492. </p>
  493. <pre>
  494. _.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
  495. =&gt; {1: [1.3], 2: [2.1, 2.4]}
  496. _.groupBy(['one', 'two', 'three'], 'length');
  497. =&gt; {3: ["one", "two"], 5: ["three"]}
  498. </pre>
  499. <p id="sortedIndex">
  500. <b class="header">sortedIndex</b><code>_.sortedIndex(list, value, [iterator])</code>
  501. <br />
  502. Uses a binary search to determine the index at which the <b>value</b>
  503. <i>should</i> be inserted into the <b>list</b> in order to maintain the <b>list</b>'s
  504. sorted order. If an <b>iterator</b> is passed, it will be used to compute
  505. the sort ranking of each value.
  506. </p>
  507. <pre>
  508. _.sortedIndex([10, 20, 30, 40, 50], 35);
  509. =&gt; 3
  510. </pre>
  511. <p id="shuffle">
  512. <b class="header">shuffle</b><code>_.shuffle(list)</code>
  513. <br />
  514. Returns a shuffled copy of the <b>list</b>, using a version of the
  515. <a href="http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle">Fisher-Yates shuffle</a>.
  516. </p>
  517. <pre>
  518. _.shuffle([1, 2, 3, 4, 5, 6]);
  519. =&gt; [4, 1, 6, 3, 5, 2]
  520. </pre>
  521. <p id="toArray">
  522. <b class="header">toArray</b><code>_.toArray(list)</code>
  523. <br />
  524. Converts the <b>list</b> (anything that can be iterated over), into a
  525. real Array. Useful for transmuting the <b>arguments</b> object.
  526. </p>
  527. <pre>
  528. (function(){ return _.toArray(arguments).slice(0); })(1, 2, 3);
  529. =&gt; [1, 2, 3]
  530. </pre>
  531. <p id="size">
  532. <b class="header">size</b><code>_.size(list)</code>
  533. <br />
  534. Return the number of values in the <b>list</b>.
  535. </p>
  536. <pre>
  537. _.size({one : 1, two : 2, three : 3});
  538. =&gt; 3
  539. </pre>
  540. <h2 id="arrays">Array Functions</h2>
  541. <p>
  542. <i>Note: All array functions will also work on the <b>arguments</b> object.</i>
  543. </p>
  544. <p id="first">
  545. <b class="header">first</b><code>_.first(array, [n])</code>
  546. <span class="alias">Alias: <b>head</b></span>
  547. <br />
  548. Returns the first element of an <b>array</b>. Passing <b>n</b> will
  549. return the first <b>n</b> elements of the array.
  550. </p>
  551. <pre>
  552. _.first([5, 4, 3, 2, 1]);
  553. =&gt; 5
  554. </pre>
  555. <p id="initial">
  556. <b class="header">initial</b><code>_.initial(array, [n])</code>
  557. <br />
  558. Returns everything but the last entry of the array. Especially useful on
  559. the arguments object. Pass <b>n</b> to exclude the last <b>n</b> elements
  560. from the result.
  561. </p>
  562. <pre>
  563. _.initial([5, 4, 3, 2, 1]);
  564. =&gt; [5, 4, 3, 2]
  565. </pre>
  566. <p id="last">
  567. <b class="header">last</b><code>_.last(array, [n])</code>
  568. <br />
  569. Returns the last element of an <b>array</b>. Passing <b>n</b> will return
  570. the last <b>n</b> elements of the array.
  571. </p>
  572. <pre>
  573. _.last([5, 4, 3, 2, 1]);
  574. =&gt; 1
  575. </pre>
  576. <p id="rest">
  577. <b class="header">rest</b><code>_.rest(array, [index])</code>
  578. <span class="alias">Alias: <b>tail</b></span>
  579. <br />
  580. Returns the <b>rest</b> of the elements in an array. Pass an <b>index</b>
  581. to return the values of the array from that index onward.
  582. </p>
  583. <pre>
  584. _.rest([5, 4, 3, 2, 1]);
  585. =&gt; [4, 3, 2, 1]
  586. </pre>
  587. <p id="compact">
  588. <b class="header">compact</b><code>_.compact(array)</code>
  589. <br />
  590. Returns a copy of the <b>array</b> with all falsy values removed.
  591. In JavaScript, <i>false</i>, <i>null</i>, <i>0</i>, <i>""</i>,
  592. <i>undefined</i> and <i>NaN</i> are all falsy.
  593. </p>
  594. <pre>
  595. _.compact([0, 1, false, 2, '', 3]);
  596. =&gt; [1, 2, 3]
  597. </pre>
  598. <p id="flatten">
  599. <b class="header">flatten</b><code>_.flatten(array)</code>
  600. <br />
  601. Flattens a nested <b>array</b> (the nesting can be to any depth).
  602. </p>
  603. <pre>
  604. _.flatten([1, [2], [3, [[[4]]]]]);
  605. =&gt; [1, 2, 3, 4];
  606. </pre>
  607. <p id="without">
  608. <b class="header">without</b><code>_.without(array, [*values])</code>
  609. <br />
  610. Returns a copy of the <b>array</b> with all instances of the <b>values</b>
  611. removed. <i>===</i> is used for the equality test.
  612. </p>
  613. <pre>
  614. _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
  615. =&gt; [2, 3, 4]
  616. </pre>
  617. <p id="union">
  618. <b class="header">union</b><code>_.union(*arrays)</code>
  619. <br />
  620. Computes the union of the passed-in <b>arrays</b>: the list of unique items,
  621. in order, that are present in one or more of the <b>arrays</b>.
  622. </p>
  623. <pre>
  624. _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  625. =&gt; [1, 2, 3, 101, 10]
  626. </pre>
  627. <p id="intersection">
  628. <b class="header">intersection</b><code>_.intersection(*arrays)</code>
  629. <br />
  630. Computes the list of values that are the intersection of all the <b>arrays</b>.
  631. Each value in the result is present in each of the <b>arrays</b>.
  632. </p>
  633. <pre>
  634. _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  635. =&gt; [1, 2]
  636. </pre>
  637. <p id="difference">
  638. <b class="header">difference</b><code>_.difference(array, *others)</code>
  639. <br />
  640. Similar to <b>without</b>, but returns the values from <b>array</b> that
  641. are not present in the <b>other</b> arrays.
  642. </p>
  643. <pre>
  644. _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  645. =&gt; [1, 3, 4]
  646. </pre>
  647. <p id="uniq">
  648. <b class="header">uniq</b><code>_.uniq(array, [isSorted], [iterator])</code>
  649. <span class="alias">Alias: <b>unique</b></span>
  650. <br />
  651. Produces a duplicate-free version of the <b>array</b>, using <i>===</i> to test
  652. object equality. If you know in advance that the <b>array</b> is sorted,
  653. passing <i>true</i> for <b>isSorted</b> will run a much faster algorithm.
  654. If you want to compute unique items based on a transformation, pass an
  655. <b>iterator</b> function.
  656. </p>
  657. <pre>
  658. _.uniq([1, 2, 1, 3, 1, 4]);
  659. =&gt; [1, 2, 3, 4]
  660. </pre>
  661. <p id="zip">
  662. <b class="header">zip</b><code>_.zip(*arrays)</code>
  663. <br />
  664. Merges together the values of each of the <b>arrays</b> with the
  665. values at the corresponding position. Useful when you have separate
  666. data sources that are coordinated through matching array indexes.
  667. If you're working with a matrix of nested arrays, <b>zip.apply</b>
  668. can transpose the matrix in a similar fashion.
  669. </p>
  670. <pre>
  671. _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
  672. =&gt; [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
  673. </pre>
  674. <p id="indexOf">
  675. <b class="header">indexOf</b><code>_.indexOf(array, value, [isSorted])</code>
  676. <br />
  677. Returns the index at which <b>value</b> can be found in the <b>array</b>,
  678. or <i>-1</i> if value is not present in the <b>array</b>. Uses the native
  679. <b>indexOf</b> function unless it's missing. If you're working with a
  680. large array, and you know that the array is already sorted, pass <tt>true</tt>
  681. for <b>isSorted</b> to use a faster binary search.
  682. </p>
  683. <pre>
  684. _.indexOf([1, 2, 3], 2);
  685. =&gt; 1
  686. </pre>
  687. <p id="lastIndexOf">
  688. <b class="header">lastIndexOf</b><code>_.lastIndexOf(array, value)</code>
  689. <br />
  690. Returns the index of the last occurrence of <b>value</b> in the <b>array</b>,
  691. or <i>-1</i> if value is not present. Uses the native <b>lastIndexOf</b>
  692. function if possible.
  693. </p>
  694. <pre>
  695. _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  696. =&gt; 4
  697. </pre>
  698. <p id="range">
  699. <b class="header">range</b><code>_.range([start], stop, [step])</code>
  700. <br />
  701. A function to create flexibly-numbered lists of integers, handy for
  702. <tt>each</tt> and <tt>map</tt> loops. <b>start</b>, if omitted, defaults
  703. to <i>0</i>; <b>step</b> defaults to <i>1</i>. Returns a list of integers
  704. from <b>start</b> to <b>stop</b>, incremented (or decremented) by <b>step</b>,
  705. exclusive.
  706. </p>
  707. <pre>
  708. _.range(10);
  709. =&gt; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  710. _.range(1, 11);
  711. =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  712. _.range(0, 30, 5);
  713. =&gt; [0, 5, 10, 15, 20, 25]
  714. _.range(0, -10, -1);
  715. =&gt; [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  716. _.range(0);
  717. =&gt; []
  718. </pre>
  719. <h2 id="functions">Function (uh, ahem) Functions</h2>
  720. <p id="bind">
  721. <b class="header">bind</b><code>_.bind(function, object, [*arguments])</code>
  722. <br />
  723. Bind a <b>function</b> to an <b>object</b>, meaning that whenever
  724. the function is called, the value of <i>this</i> will be the <b>object</b>.
  725. Optionally, bind <b>arguments</b> to the <b>function</b> to pre-fill them,
  726. also known as <b>partial application</b>.
  727. </p>
  728. <pre>
  729. var func = function(greeting){ return greeting + ': ' + this.name };
  730. func = _.bind(func, {name : 'moe'}, 'hi');
  731. func();
  732. =&gt; 'hi: moe'
  733. </pre>
  734. <p id="bindAll">
  735. <b class="header">bindAll</b><code>_.bindAll(object, [*methodNames])</code>
  736. <br />
  737. Binds a number of methods on the <b>object</b>, specified by
  738. <b>methodNames</b>, to be run in the context of that object whenever they
  739. are invoked. Very handy for binding functions that are going to be used
  740. as event handlers, which would otherwise be invoked with a fairly useless
  741. <i>this</i>. If no <b>methodNames</b> are provided, all of the object's
  742. function properties will be bound to it.
  743. </p>
  744. <pre>
  745. var buttonView = {
  746. label : 'underscore',
  747. onClick : function(){ alert('clicked: ' + this.label); },
  748. onHover : function(){ console.log('hovering: ' + this.label); }
  749. };
  750. _.bindAll(buttonView);
  751. jQuery('#underscore_button').bind('click', buttonView.onClick);
  752. =&gt; When the button is clicked, this.label will have the correct value...
  753. </pre>
  754. <p id="memoize">
  755. <b class="header">memoize</b><code>_.memoize(function, [hashFunction])</code>
  756. <br />
  757. Memoizes a given <b>function</b> by caching the computed result. Useful
  758. for speeding up slow-running computations. If passed an optional
  759. <b>hashFunction</b>, it will be used to compute the hash key for storing
  760. the result, based on the arguments to the original function. The default
  761. <b>hashFunction</b> just uses the first argument to the memoized function
  762. as the key.
  763. </p>
  764. <pre>
  765. var fibonacci = _.memoize(function(n) {
  766. return n &lt; 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  767. });
  768. </pre>
  769. <p id="delay">
  770. <b class="header">delay</b><code>_.delay(function, wait, [*arguments])</code>
  771. <br />
  772. Much like <b>setTimeout</b>, invokes <b>function</b> after <b>wait</b>
  773. milliseconds. If you pass the optional <b>arguments</b>, they will be
  774. forwarded on to the <b>function</b> when it is invoked.
  775. </p>
  776. <pre>
  777. var log = _.bind(console.log, console);
  778. _.delay(log, 1000, 'logged later');
  779. =&gt; 'logged later' // Appears after one second.
  780. </pre>
  781. <p id="defer">
  782. <b class="header">defer</b><code>_.defer(function)</code>
  783. <br />
  784. Defers invoking the <b>function</b> until the current call stack has cleared,
  785. similar to using <b>setTimeout</b> with a delay of 0. Useful for performing
  786. expensive computations or HTML rendering in chunks without blocking the UI thread
  787. from updating.
  788. </p>
  789. <pre>
  790. _.defer(function(){ alert('deferred'); });
  791. // Returns from the function before the alert runs.
  792. </pre>
  793. <p id="throttle">
  794. <b class="header">throttle</b><code>_.throttle(function, wait)</code>
  795. <br />
  796. Creates and returns a new, throttled version of the passed function,
  797. that, when invoked repeatedly, will only actually call the original function
  798. at most once per every <b>wait</b>
  799. milliseconds. Useful for rate-limiting events that occur faster than you
  800. can keep up with.
  801. </p>
  802. <pre>
  803. var throttled = _.throttle(updatePosition, 100);
  804. $(window).scroll(throttled);
  805. </pre>
  806. <p id="debounce">
  807. <b class="header">debounce</b><code>_.debounce(function, wait)</code>
  808. <br />
  809. Creates and returns a new debounced version of the passed function that
  810. will postpone its execution until after
  811. <b>wait</b> milliseconds have elapsed since the last time it
  812. was invoked. Useful for implementing behavior that should only happen
  813. <i>after</i> the input has stopped arriving. For example: rendering a
  814. preview of a Markdown comment, recalculating a layout after the window
  815. has stopped being resized, and so on.
  816. </p>
  817. <pre>
  818. var lazyLayout = _.debounce(calculateLayout, 300);
  819. $(window).resize(lazyLayout);
  820. </pre>
  821. <p id="once">
  822. <b class="header">once</b><code>_.once(function)</code>
  823. <br />
  824. Creates a version of the function that can only be called one time.
  825. Repeated calls to the modified function will have no effect, returning
  826. the value from the original call. Useful for initialization functions,
  827. instead of having to set a boolean flag and then check it later.
  828. </p>
  829. <pre>
  830. var initialize = _.once(createApplication);
  831. initialize();
  832. initialize();
  833. // Application is only created once.
  834. </pre>
  835. <p id="after">
  836. <b class="header">after</b><code>_.after(count, function)</code>
  837. <br />
  838. Creates a version of the function that will only be run after first
  839. being called <b>count</b> times. Useful for grouping asynchronous responses,
  840. where you want to be sure that all the async calls have finished, before
  841. proceeding.
  842. </p>
  843. <pre>
  844. var renderNotes = _.after(notes.length, render);
  845. _.each(notes, function(note) {
  846. note.asyncSave({success: renderNotes});
  847. });
  848. // renderNotes is run once, after all notes have saved.
  849. </pre>
  850. <p id="wrap">
  851. <b class="header">wrap</b><code>_.wrap(function, wrapper)</code>
  852. <br />
  853. Wraps the first <b>function</b> inside of the <b>wrapper</b> function,
  854. passing it as the first argument. This allows the <b>wrapper</b> to
  855. execute code before and after the <b>function</b> runs, adjust the arguments,
  856. and execute it conditionally.
  857. </p>
  858. <pre>
  859. var hello = function(name) { return "hello: " + name; };
  860. hello = _.wrap(hello, function(func) {
  861. return "before, " + func("moe") + ", after";
  862. });
  863. hello();
  864. =&gt; 'before, hello: moe, after'
  865. </pre>
  866. <p id="compose">
  867. <b class="header">compose</b><code>_.compose(*functions)</code>
  868. <br />
  869. Returns the composition of a list of <b>functions</b>, where each function
  870. consumes the return value of the function that follows. In math terms,
  871. composing the functions <i>f()</i>, <i>g()</i>, and <i>h()</i> produces
  872. <i>f(g(h()))</i>.
  873. </p>
  874. <pre>
  875. var greet = function(name){ return "hi: " + name; };
  876. var exclaim = function(statement){ return statement + "!"; };
  877. var welcome = _.compose(exclaim, greet);
  878. welcome('moe');
  879. =&gt; 'hi: moe!'
  880. </pre>
  881. <h2 id="objects">Object Functions</h2>
  882. <p id="keys">
  883. <b class="header">keys</b><code>_.keys(object)</code>
  884. <br />
  885. Retrieve all the names of the <b>object</b>'s properties.
  886. </p>
  887. <pre>
  888. _.keys({one : 1, two : 2, three : 3});
  889. =&gt; ["one", "two", "three"]
  890. </pre>
  891. <p id="values">
  892. <b class="header">values</b><code>_.values(object)</code>
  893. <br />
  894. Return all of the values of the <b>object</b>'s properties.
  895. </p>
  896. <pre>
  897. _.values({one : 1, two : 2, three : 3});
  898. =&gt; [1, 2, 3]
  899. </pre>
  900. <p id="functions">
  901. <b class="header">functions</b><code>_.functions(object)</code>
  902. <span class="alias">Alias: <b>methods</b></span>
  903. <br />
  904. Returns a sorted list of the names of every method in an object &mdash;
  905. that is to say, the name of every function property of the object.
  906. </p>
  907. <pre>
  908. _.functions(_);
  909. =&gt; ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...
  910. </pre>
  911. <p id="extend">
  912. <b class="header">extend</b><code>_.extend(destination, *sources)</code>
  913. <br />
  914. Copy all of the properties in the <b>source</b> objects over to the
  915. <b>destination</b> object. It's in-order, so the last source will override
  916. properties of the same name in previous arguments.
  917. </p>
  918. <pre>
  919. _.extend({name : 'moe'}, {age : 50});
  920. =&gt; {name : 'moe', age : 50}
  921. </pre>
  922. <p id="defaults">
  923. <b class="header">defaults</b><code>_.defaults(object, *defaults)</code>
  924. <br />
  925. Fill in missing properties in <b>object</b> with default values from the
  926. <b>defaults</b> objects. As soon as the property is filled, further defaults
  927. will have no effect.
  928. </p>
  929. <pre>
  930. var iceCream = {flavor : "chocolate"};
  931. _.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"});
  932. =&gt; {flavor : "chocolate", sprinkles : "lots"}
  933. </pre>
  934. <p id="clone">
  935. <b class="header">clone</b><code>_.clone(object)</code>
  936. <br />
  937. Create a shallow-copied clone of the <b>object</b>. Any nested objects
  938. or arrays will be copied by reference, not duplicated.
  939. </p>
  940. <pre>
  941. _.clone({name : 'moe'});
  942. =&gt; {name : 'moe'};
  943. </pre>
  944. <p id="tap">
  945. <b class="header">tap</b><code>_.tap(object, interceptor)</code>
  946. <br />
  947. Invokes <b>interceptor</b> with the <b>object</b>, and then returns <b>object</b>.
  948. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
  949. </p>
  950. <pre>
  951. _.chain([1,2,3,200])
  952. .filter(function(num) { return num % 2 == 0; })
  953. .tap(console.log)
  954. .map(function(num) { return num * num })
  955. .value();
  956. =&gt; [2, 200]
  957. =&gt; [4, 40000]
  958. </pre>
  959. <p id="isEqual">
  960. <b class="header">isEqual</b><code>_.isEqual(object, other)</code>
  961. <br />
  962. Performs an optimized deep comparison between the two objects, to determine
  963. if they should be considered equal.
  964. </p>
  965. <pre>
  966. var moe = {name : 'moe', luckyNumbers : [13, 27, 34]};
  967. var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
  968. moe == clone;
  969. =&gt; false
  970. _.isEqual(moe, clone);
  971. =&gt; true
  972. </pre>
  973. <p id="isEmpty">
  974. <b class="header">isEmpty</b><code>_.isEmpty(object)</code>
  975. <br />
  976. Returns <i>true</i> if <b>object</b> contains no values.
  977. </p>
  978. <pre>
  979. _.isEmpty([1, 2, 3]);
  980. =&gt; false
  981. _.isEmpty({});
  982. =&gt; true
  983. </pre>
  984. <p id="isElement">
  985. <b class="header">isElement</b><code>_.isElement(object)</code>
  986. <br />
  987. Returns <i>true</i> if <b>object</b> is a DOM element.
  988. </p>
  989. <pre>
  990. _.isElement(jQuery('body')[0]);
  991. =&gt; true
  992. </pre>
  993. <p id="isArray">
  994. <b class="header">isArray</b><code>_.isArray(object)</code>
  995. <br />
  996. Returns <i>true</i> if <b>object</b> is an Array.
  997. </p>
  998. <pre>
  999. (function(){ return _.isArray(arguments); })();
  1000. =&gt; false
  1001. _.isArray([1,2,3]);
  1002. =&gt; true
  1003. </pre>
  1004. <p id="isArguments">
  1005. <b class="header">isArguments</b><code>_.isArguments(object)</code>
  1006. <br />
  1007. Returns <i>true</i> if <b>object</b> is an Arguments object.
  1008. </p>
  1009. <pre>
  1010. (function(){ return _.isArguments(arguments); })(1, 2, 3);
  1011. =&gt; true
  1012. _.isArguments([1,2,3]);
  1013. =&gt; false
  1014. </pre>
  1015. <p id="isFunction">
  1016. <b class="header">isFunction</b><code>_.isFunction(object)</code>
  1017. <br />
  1018. Returns <i>true</i> if <b>object</b> is a Function.
  1019. </p>
  1020. <pre>
  1021. _.isFunction(alert);
  1022. =&gt; true
  1023. </pre>
  1024. <p id="isString">
  1025. <b class="header">isString</b><code>_.isString(object)</code>
  1026. <br />
  1027. Returns <i>true</i> if <b>object</b> is a String.
  1028. </p>
  1029. <pre>
  1030. _.isString("moe");
  1031. =&gt; true
  1032. </pre>
  1033. <p id="isNumber">
  1034. <b class="header">isNumber</b><code>_.isNumber(object)</code>
  1035. <br />
  1036. Returns <i>true</i> if <b>object</b> is a Number (including <tt>NaN</tt>).
  1037. </p>
  1038. <pre>
  1039. _.isNumber(8.4 * 5);
  1040. =&gt; true
  1041. </pre>
  1042. <p id="isBoolean">
  1043. <b class="header">isBoolean</b><code>_.isBoolean(object)</code>
  1044. <br />
  1045. Returns <i>true</i> if <b>object</b> is either <i>true</i> or <i>false</i>.
  1046. </p>
  1047. <pre>
  1048. _.isBoolean(null);
  1049. =&gt; false
  1050. </pre>
  1051. <p id="isDate">
  1052. <b class="header">isDate</b><code>_.isDate(object)</code>
  1053. <br />
  1054. Returns <i>true</i> if <b>object</b> is a Date.
  1055. </p>
  1056. <pre>
  1057. _.isDate(new Date());
  1058. =&gt; true
  1059. </pre>
  1060. <p id="isRegExp">
  1061. <b class="header">isRegExp</b><code>_.isRegExp(object)</code>
  1062. <br />
  1063. Returns <i>true</i> if <b>object</b> is a RegExp.
  1064. </p>
  1065. <pre>
  1066. _.isRegExp(/moe/);
  1067. =&gt; true
  1068. </pre>
  1069. <p id="isNaN">
  1070. <b class="header">isNaN</b><code>_.isNaN(object)</code>
  1071. <br />
  1072. Returns <i>true</i> if <b>object</b> is <i>NaN</i>.<br /> Note: this is not
  1073. the same as the native <b>isNaN</b> function, which will also return
  1074. true if the variable is <i>undefined</i>.
  1075. </p>
  1076. <pre>
  1077. _.isNaN(NaN);
  1078. =&gt; true
  1079. isNaN(undefined);
  1080. =&gt; true
  1081. _.isNaN(undefined);
  1082. =&gt; false
  1083. </pre>
  1084. <p id="isNull">
  1085. <b class="header">isNull</b><code>_.isNull(object)</code>
  1086. <br />
  1087. Returns <i>true</i> if the value of <b>object</b> is <i>null</i>.
  1088. </p>
  1089. <pre>
  1090. _.isNull(null);
  1091. =&gt; true
  1092. _.isNull(undefined);
  1093. =&gt; false
  1094. </pre>
  1095. <p id="isUndefined">
  1096. <b class="header">isUndefined</b><code>_.isUndefined(variable)</code>
  1097. <br />
  1098. Returns <i>true</i> if <b>variable</b> is <i>undefined</i>.
  1099. </p>
  1100. <pre>
  1101. _.isUndefined(window.missingVariable);
  1102. =&gt; true
  1103. </pre>
  1104. <h2 id="utility">Utility Functions</h2>
  1105. <p id="noConflict">
  1106. <b class="header">noConflict</b><code>_.noConflict()</code>
  1107. <br />
  1108. Give control of the "_" variable back to its previous owner. Returns
  1109. a reference to the <b>Underscore</b> object.
  1110. </p>
  1111. <pre>
  1112. var underscore = _.noConflict();</pre>
  1113. <p id="identity">
  1114. <b class="header">identity</b><code>_.identity(value)</code>
  1115. <br />
  1116. Returns the same value that is used as the argument. In math:
  1117. <tt>f(x) = x</tt><br />
  1118. This function looks useless, but is used throughout Underscore as
  1119. a default iterator.
  1120. </p>
  1121. <pre>
  1122. var moe = {name : 'moe'};
  1123. moe === _.identity(moe);
  1124. =&gt; true</pre>
  1125. <p id="times">
  1126. <b class="header">times</b><code>_.times(n, iterator)</code>
  1127. <br />
  1128. Invokes the given iterator function <b>n</b> times.
  1129. </p>
  1130. <pre>
  1131. _(3).times(function(){ genie.grantWish(); });</pre>
  1132. <p id="mixin">
  1133. <b class="header">mixin</b><code>_.mixin(object)</code>
  1134. <br />
  1135. Allows you to extend Underscore with your own utility functions. Pass
  1136. a hash of <tt>{name: function}</tt> definitions to have your functions
  1137. added to the Underscore object, as well as the OOP wrapper.
  1138. </p>
  1139. <pre>
  1140. _.mixin({
  1141. capitalize : function(string) {
  1142. return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  1143. }
  1144. });
  1145. _("fabio").capitalize();
  1146. =&gt; "Fabio"
  1147. </pre>
  1148. <p id="uniqueId">
  1149. <b class="header">uniqueId</b><code>_.uniqueId([prefix])</code>
  1150. <br />
  1151. Generate a globally-unique id for client-side models or DOM elements
  1152. that need one. If <b>prefix</b> is passed, the id will be appended to it.
  1153. </p>
  1154. <pre>
  1155. _.uniqueId('contact_');
  1156. =&gt; 'contact_104'</pre>
  1157. <p id="escape">
  1158. <b class="header">escape</b><code>_.escape(string)</code>
  1159. <br />
  1160. Escapes a string for insertion into HTML, replacing
  1161. <tt>&amp;</tt>, <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&quot;</tt>, <tt>&#x27;</tt>, and <tt>&#x2F;</tt> characters.
  1162. </p>
  1163. <pre>
  1164. _.escape('Curly, Larry &amp; Moe');
  1165. =&gt; "Curly, Larry &amp;amp; Moe"</pre>
  1166. <p id="template">
  1167. <b class="header">template</b><code>_.template(templateString, [context])</code>
  1168. <br />
  1169. Compiles JavaScript templates into functions that can be evaluated
  1170. for rendering. Useful for rendering complicated bits of HTML from JSON
  1171. data sources. Template functions can both interpolate variables, using<br />
  1172. <tt>&lt;%= &hellip; %&gt;</tt>, as well as execute arbitrary JavaScript code, with
  1173. <tt>&lt;% &hellip; %&gt;</tt>. If you wish to interpolate a value, and have
  1174. it be HTML-escaped, use <tt>&lt;%- &hellip; %&gt;</tt> When you evaluate a template function, pass in a
  1175. <b>context</b> object that has properties corresponding to the template's free
  1176. variables. If you're writing a one-off, you can pass the <b>context</b>
  1177. object as the second parameter to <b>template</b> in order to render
  1178. immediately instead of returning a template function.
  1179. </p>
  1180. <pre>
  1181. var compiled = _.template("hello: &lt;%= name %&gt;");
  1182. compiled({name : 'moe'});
  1183. =&gt; "hello: moe"
  1184. var list = "&lt;% _.each(people, function(name) { %&gt; &lt;li&gt;&lt;%= name %&gt;&lt;/li&gt; &lt;% }); %&gt;";
  1185. _.template(list, {people : ['moe', 'curly', 'larry']});
  1186. =&gt; "&lt;li&gt;moe&lt;/li&gt;&lt;li&gt;curly&lt;/li&gt;&lt;li&gt;larry&lt;/li&gt;"
  1187. var template = _.template("&lt;b&gt;&lt;%- value %&gt;&lt;/b&gt;");
  1188. template({value : '&lt;script&gt;'});
  1189. =&gt; "&lt;b&gt;&amp;lt;script&amp;gt;&lt;/b&gt;"</pre>
  1190. <p>
  1191. You can also use <tt>print</tt> from within JavaScript code. This is
  1192. sometimes more convenient than using <tt>&lt;%= ... %&gt;</tt>.
  1193. </p>
  1194. <pre>
  1195. var compiled = _.template("&lt;% print('Hello ' + epithet); %&gt;");
  1196. compiled({epithet: "stooge"});
  1197. =&gt; "Hello stooge."</pre>
  1198. <p>
  1199. If ERB-style delimiters aren't your cup of tea, you can change Underscore's
  1200. template settings to use different symbols to set off interpolated code.
  1201. Define an <b>interpolate</b> regex to match expressions that should be
  1202. interpolated verbatim, an <b>escape</b> regex to match expressions that should
  1203. be inserted after being HTML escaped, and an <b>evaluate</b> regex to match
  1204. expressions that should be evaluated without insertion into the resulting
  1205. string. You may define or omit any combination of the three.
  1206. For example, to perform
  1207. <a href="http://github.com/janl/mustache.js#readme">Mustache.js</a>
  1208. style templating:
  1209. </p>
  1210. <pre>
  1211. _.templateSettings = {
  1212. interpolate : /\{\{(.+?)\}\}/g
  1213. };
  1214. var template = _.template("Hello {{ name }}!");
  1215. template({name : "Mustache"});
  1216. =&gt; "Hello Mustache!"</pre>
  1217. <h2 id="chaining">Chaining</h2>
  1218. <p>
  1219. You can use Underscore in either an object-oriented or a functional style,
  1220. depending on your preference. The following two lines of code are
  1221. identical ways to double a list of numbers.
  1222. </p>
  1223. <pre>
  1224. _.map([1, 2, 3], function(n){ return n * 2; });
  1225. _([1, 2, 3]).map(function(n){ return n * 2; });</pre>
  1226. <p>
  1227. Using the object-oriented style allows you to chain together methods. Calling
  1228. <tt>chain</tt> on a wrapped object will cause all future method calls to
  1229. return wrapped objects as well. When you've finished the computation,
  1230. use <tt>value</tt> to retrieve the final value. Here's an example of chaining
  1231. together a <b>map/flatten/reduce</b>, in order to get the word count of
  1232. every word in a song.
  1233. </p>
  1234. <pre>
  1235. var lyrics = [
  1236. {line : 1, words : "I'm a lumberjack and I'm okay"},
  1237. {line : 2, words : "I sleep all night and I work all day"},
  1238. {line : 3, words : "He's a lumberjack and he's okay"},
  1239. {line : 4, words : "He sleeps all night and he works all day"}
  1240. ];
  1241. _.chain(lyrics)
  1242. .map(function(line) { return line.words.split(' '); })
  1243. .flatten()
  1244. .reduce(function(counts, word) {
  1245. counts[word] = (counts[word] || 0) + 1;
  1246. return counts;
  1247. }, {}).value();
  1248. =&gt; {lumberjack : 2, all : 4, night : 2 ... }</pre>
  1249. <p>
  1250. In addition, the
  1251. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/prototype">Array prototype's methods</a>
  1252. are proxied through the chained Underscore object, so you can slip a
  1253. <tt>reverse</tt> or a <tt>push</tt> into your chain, and continue to
  1254. modify the array.
  1255. </p>
  1256. <p id="chain">
  1257. <b class="header">chain</b><code>_.chain(obj)</code>
  1258. <br />
  1259. Returns a wrapped object. Calling methods on this object will continue
  1260. to return wrapped objects until <tt>value</tt> is used.
  1261. </p>
  1262. <pre>
  1263. var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
  1264. var youngest = _.chain(stooges)
  1265. .sortBy(function(stooge){ return stooge.age; })
  1266. .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  1267. .first()
  1268. .value();
  1269. =&gt; "moe is 21"
  1270. </pre>
  1271. <p id="value">
  1272. <b class="header">value</b><code>_(obj).value()</code>
  1273. <br />
  1274. Extracts the value of a wrapped object.
  1275. </p>
  1276. <pre>
  1277. _([1, 2, 3]).value();
  1278. =&gt; [1, 2, 3]
  1279. </pre>
  1280. <h2 id="links">Links &amp; Suggested Reading</h2>
  1281. <p>
  1282. <a href="http://mirven.github.com/underscore.lua/">Underscore.lua</a>,
  1283. a Lua port of the functions that are applicable in both languages.
  1284. Includes OOP-wrapping and chaining.
  1285. The <a href="http://github.com/mirven/underscore.lua">source</a> is
  1286. available on GitHub.
  1287. </p>
  1288. <p>
  1289. <a href="http://brianhaveri.github.com/Underscore.php/">Underscore.php</a>,
  1290. a PHP port of the functions that are applicable in both languages.
  1291. Includes OOP-wrapping and chaining.
  1292. The <a href="http://github.com/brianhaveri/Underscore.php">source</a> is
  1293. available on GitHub.
  1294. </p>
  1295. <p>
  1296. <a href="http://vti.github.com/underscore-perl/">Underscore-perl</a>,
  1297. a Perl port of many of the Underscore.js functions,
  1298. aimed at on Perl hashes and arrays, also
  1299. <a href="https://github.com/vti/underscore-perl/">available on GitHub</a>.
  1300. </p>
  1301. <p>
  1302. <a href="https://github.com/edtsech/underscore.string">Underscore.string</a>,
  1303. an Underscore extension that adds functions for string-manipulation:
  1304. <tt>trim</tt>, <tt>startsWith</tt>, <tt>contains</tt>, <tt>capitalize</tt>,
  1305. <tt>reverse</tt>, <tt>sprintf</tt>, and more.
  1306. </p>
  1307. <p>
  1308. Ruby's <a href="http://ruby-doc.org/core/classes/Enumerable.html">Enumerable</a> module.
  1309. </p>
  1310. <p>
  1311. <a href="http://www.prototypejs.org/">Prototype.js</a>, which provides
  1312. JavaScript with collection functions in the manner closest to Ruby's Enumerable.
  1313. </p>
  1314. <p>
  1315. Oliver Steele's
  1316. <a href="http://osteele.com/sources/javascript/functional/">Functional JavaScript</a>,
  1317. which includes comprehensive higher-order function support as well as string lambdas.
  1318. </p>
  1319. <p>
  1320. Michael Aufreiter's <a href="http://substance.io/#michael/data-js">Data.js</a>,
  1321. a data manipulation + persistence library for JavaScript.
  1322. </p>
  1323. <p>
  1324. Python's <a href="http://docs.python.org/library/itertools.html">itertools</a>.
  1325. </p>
  1326. <h2 id="changelog">Change Log</h2>
  1327. <p>
  1328. <b class="header">1.2.4</b> &mdash; <small><i>Jan. 4, 2012</i></small><br />
  1329. <ul>
  1330. <li>
  1331. You now can (and probably should) write <tt>_.chain(list)</tt>
  1332. instead of <tt>_(list).chain()</tt>.
  1333. </li

Large files files are truncated, but you can click here to view the full file