PageRenderTime 61ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/node_modules/underscore/index.html

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

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