Movatterモバイル変換


[0]ホーム

URL:


Underscore.js(1.13.7)
Introduction
Collections
Arrays
Functions
Objects
Utility
OOP Style
Chaining
Links
Notes
Change Log

Underscore.js

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?” … and the tie to go along withjQuery's tux andBackbone's suspenders.

Underscore provides over 100 functions that support both your favorite workaday functional helpers:map,filter,invoke — as well as more specialized goodies: function binding, javascript templating, creating quick indexes, deep equality testing, and so on.

A completeTest Suite is included for your perusal.

You may also read through theannotated source code. There is amodular version with clickable import references as well.

You may choose between monolithic and modular imports. There is a quick summary of the options below, as well as a more comprehensive discussion inthe article.

Enjoying Underscore, and want toturn it up to 11? TryUnderscore-contrib.

The project ishosted on GitHub. You can report bugs and discuss features on theissues page or chat in theGitter channel.

You can support the project by donating onPatreon. Enterprise coverage is available as part of theTidelift Subscription.

Underscore is an open-source component ofDocumentCloud.

v1.13.7 Downloads(Right-click, and use "Save As")

ESM (Development)65.9 KB, Uncompressed with Plentiful Comments  (Source Map)
ESM (Production)8.59 KB, Minified and Gzipped  (Source Map)
UMD (Development)68.4 KB, Uncompressed with Bountiful Comments  (Source Map)
UMD (Production)7.48 KB, Minified and Gzipped  (Source Map)
Edge ESMUnreleased, currentmaster, use by your own judgement and at your own risk
Edge UMDUnreleased, currentmaster, use if you’re feeling lucky

v1.13.7 CDN URLs(Use with<script src="..."></script>)

In most cases, you can replace the version number above bylatest so that your embed will automatically use the latest version, orstable if you want to delay updating until an update has proven to be free of accidental breaking changes. Example:
https://cdn.jsdelivr.net/npm/underscore@latest/underscore-umd-min.js

Package Installation

If you are hardcoding the path to the file within the package and you are unsure which build to use, it is very likely that you needunderscore-umd.js or the minified variantunderscore-umd-min.js.

Monolithic Import (recommended)

Modular Import

For functions with multiple aliases, the file name of the module is always thefirst name that appears in the documentation. For example,_.reduce/_.inject/_.foldl is exported fromunderscore/modules/reduce.js. Modular usage is mostly recommended for creating a customized build of Underscore.

Engine Compatibility

Underscore 1.x is backwards compatible with any engine that fully supports ES3, while also utilizing newer features when available, such asObject.keys, typed arrays and ES modules. We routinely run our unittests against the JavaScript engines listed below:

In addition:

Underscore 2.x will likely remove support for some outdated environments.

Collection Functions (Arrays or Objects)

each_.each(list, iteratee, [context])Alias:forEachsource
Iterates over alist of elements, yielding each in turn to aniteratee function. Theiteratee is bound to thecontext object, if one is passed. Each invocation ofiteratee is called with three arguments:(element, index, list). Iflist is a JavaScript object,iteratee's arguments will be(value, key, list). Returns thelist for chaining.

_.each([1, 2, 3], alert);=> alerts each number in turn..._.each({one: 1, two: 2, three: 3}, alert);=> alerts each number value in turn...

Note: Collection functions work on arrays, objects, and array-like objects such asarguments,NodeList and similar. But it works by duck-typing, so avoid passing objects with a numericlength property. It's also good to note that aneach loop cannot be broken out of — to break, use_.find instead.

map_.map(list, iteratee, [context])Alias:collectsource
Produces a new array of values by mapping each value inlist through a transformation function (iteratee). The iteratee is passed three arguments: thevalue, then theindex (orkey) of the iteration, and finally a reference to the entirelist.

_.map([1, 2, 3], function(num){ return num * 3; });=> [3, 6, 9]_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });=> [3, 6, 9]_.map([[1, 2], [3, 4]], _.first);=> [1, 3]

reduce_.reduce(list, iteratee, [memo], [context])Aliases:inject,foldlsource
Also known asinject andfoldl, reduce boils down alist of values into a single value.Memo is the initial state of the reduction, and each successive step of it should be returned byiteratee. The iteratee is passed four arguments: thememo, then thevalue andindex (or key) of the iteration, and finally a reference to the entirelist.

If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list. The first element is instead passed as the memo in the invocation of the iteratee on the next element in the list.

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

reduceRight_.reduceRight(list, iteratee, [memo], [context])Alias:foldrsource
The right-associative version ofreduce.Foldr is not as useful in JavaScript as it would be in a language with lazy evaluation.

var list = [[0, 1], [2, 3], [4, 5]];var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);=> [4, 5, 2, 3, 0, 1]

find_.find(list, predicate, [context])Alias:detectsource
Looks through each value in thelist, returning the first one that passes a truth test (predicate), orundefined if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.predicate is transformed throughiteratee to facilitate shorthand syntaxes.

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

filter_.filter(list, predicate, [context])Alias:selectsource
Looks through each value in thelist, returning an array of all the values that pass a truth test (predicate).predicate is transformed throughiteratee to facilitate shorthand syntaxes.

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

findWhere_.findWhere(list, properties)source
Looks through thelist and returns thefirst value thatmatches all of the key-value pairs listed inproperties.

If no match is found, or iflist is empty,undefined will be returned.

_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});=> {year: 1918, newsroom: "The New York Times",  reason: "For its public service in publishing in full so many official reports,  documents and speeches by European statesmen relating to the progress and  conduct of the war."}

where_.where(list, properties)source
Looks through each value in thelist, returning an array of all the values thatmatches the key-value pairs listed inproperties.

_.where(listOfPlays, {author: "Shakespeare", year: 1611});=> [{title: "Cymbeline", author: "Shakespeare", year: 1611},    {title: "The Tempest", author: "Shakespeare", year: 1611}]

reject_.reject(list, predicate, [context])source
Returns the values inlist without the elements that the truth test (predicate) passes. The opposite offilter.predicate is transformed throughiteratee to facilitate shorthand syntaxes.

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

every_.every(list, [predicate], [context])Alias:allsource
Returnstrue if all of the values in thelist pass thepredicate truth test. Short-circuits and stops traversing the list if a false element is found.predicate is transformed throughiteratee to facilitate shorthand syntaxes.

_.every([2, 4, 5], function(num) { return num % 2 == 0; });=> false

some_.some(list, [predicate], [context])Alias:anysource
Returnstrue if any of the values in thelist pass thepredicate truth test. Short-circuits and stops traversing the list if a true element is found.predicate is transformed throughiteratee to facilitate shorthand syntaxes.

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

contains_.contains(list, value, [fromIndex])Aliases:include,includessource
Returnstrue if thevalue is present in thelist. UsesindexOf internally, iflist is an Array. UsefromIndex to start your search at a given index.

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

invoke_.invoke(list, methodName, *arguments)source
Calls the method named bymethodName on each value in thelist. Any extra arguments passed toinvoke will be forwarded on to the method invocation.

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

pluck_.pluck(list, propertyName)source
A convenient version of what is perhaps the most common use-case formap: extracting a list of property values.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];_.pluck(stooges, 'name');=> ["moe", "larry", "curly"]

max_.max(list, [iteratee], [context])source
Returns the maximum value inlist. If aniteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked.-Infinity is returned iflist is empty, so anisEmpty guard may be required. This function can currently only compare numbers reliably. This function uses operator< (note).

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];_.max(stooges, function(stooge){ return stooge.age; });=> {name: 'curly', age: 60};

min_.min(list, [iteratee], [context])source
Returns the minimum value inlist. If aniteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked.Infinity is returned iflist is empty, so anisEmpty guard may be required. This function can currently only compare numbers reliably. This function uses operator< (note).

var numbers = [10, 5, 100, 2, 1000];_.min(numbers);=> 2

sortBy_.sortBy(list, iteratee, [context])source
Returns a (stably) sorted copy oflist, ranked in ascending order by the results of running each value throughiteratee. iteratee may also be the string name of the property to sort by (eg.length). This function uses operator< (note).

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });=> [5, 4, 6, 3, 1, 2]var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];_.sortBy(stooges, 'name');=> [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];

groupBy_.groupBy(list, iteratee, [context])source
Splits a collection into sets, grouped by the result of running each value throughiteratee. Ifiteratee is a string instead of a function, groups by the property named byiteratee on each of the values.

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });=> {1: [1.3], 2: [2.1, 2.4]}_.groupBy(['one', 'two', 'three'], 'length');=> {3: ["one", "two"], 5: ["three"]}

indexBy_.indexBy(list, iteratee, [context])source
Given alist, and aniteratee function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just likegroupBy, but for when you know your keys are unique.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];_.indexBy(stooges, 'age');=> {  "40": {name: 'moe', age: 40},  "50": {name: 'larry', age: 50},  "60": {name: 'curly', age: 60}}

countBy_.countBy(list, iteratee, [context])source
Sorts a list into groups and returns a count for the number of objects in each group. Similar togroupBy, but instead of returning a list of values, returns a count for the number of values in that group.

_.countBy([1, 2, 3, 4, 5], function(num) {  return num % 2 == 0 ? 'even': 'odd';});=> {odd: 3, even: 2}

shuffle_.shuffle(list)source
Returns a shuffled copy of thelist, using a version of theFisher-Yates shuffle.

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

sample_.sample(list, [n])source
Produce a random sample from thelist. Pass a number to returnn random elements from the list. Otherwise a single random item will be returned.

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

toArray_.toArray(list)source
Creates a real Array from thelist (anything that can be iterated over). Useful for transmuting thearguments object.

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

size_.size(list)source
Return the number of values in thelist.

_.size([1, 2, 3, 4, 5]);=> 5_.size({one: 1, two: 2, three: 3});=> 3

partition_.partition(list, predicate)source
Splitlist into two arrays: one whose elements all satisfypredicate and one whose elements all do not satisfypredicate.predicate is transformed throughiteratee to facilitate shorthand syntaxes.

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

compact_.compact(list)source
Returns a copy of thelist with all falsy values removed. In JavaScript,false,null,0,"",undefined andNaN are all falsy.

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

Array Functions

Note: All array functions will also work on thearguments object. However, Underscore functions are not designed to work on "sparse" arrays.

first_.first(array, [n])Aliases:head,takesource
Returns the first element of anarray. Passingn will return the firstn elements of the array.

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

initial_.initial(array, [n])source
Returns everything but the last entry of the array. Especially useful on the arguments object. Passn to exclude the lastn elements from the result.

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

last_.last(array, [n])source
Returns the last element of anarray. Passingn will return the lastn elements of the array.

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

rest_.rest(array, [index])Aliases:tail,dropsource
Returns therest of the elements in an array. Pass anindex to return the values of the array from that index onward.

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

flatten_.flatten(array, [depth])source
Flattens a nestedarray. If you passtrue or1 as thedepth, the array will only be flattened a single level. Passing a greater number will cause the flattening to descend deeper into the nesting hierarchy. Omitting thedepth argument, or passingfalse orInfinity, flattens the array all the way to the deepest nesting level.

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

without_.without(array, *values)source
Returns a copy of thearray with all instances of thevalues removed.

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

union_.union(*arrays)source
Computes the union of the passed-inarrays: the list of unique items, in order, that are present in one or more of thearrays.

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

intersection_.intersection(*arrays)source
Computes the list of values that are the intersection of all thearrays. Each value in the result is present in each of thearrays.

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

difference_.difference(array, *others)source
Similar towithout, but returns the values fromarray that are not present in theother arrays.

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

uniq_.uniq(array, [isSorted], [iteratee])Alias:uniquesource
Produces a duplicate-free version of thearray, using=== to test object equality. In particular only the first occurrence of each value is kept. If you know in advance that thearray is sorted, passingtrue forisSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass aniteratee function.

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

zip_.zip(*arrays)source
Merges together the values of each of thearrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.

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

unzip_.unzip(array)Alias:transposesource
The opposite ofzip. Given anarray of arrays, returns a series of new arrays, the first of which contains all of the first elements in the input arrays, the second of which contains all of the second elements, and so on. If you're working with a matrix of nested arrays, this can be used to transpose the matrix.

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

object_.object(list, [values])source
Converts arrays into objects. Pass either a single list of[key, value] pairs, or a list of keys, and a list of values. Passing by pairs is the reverse ofpairs. If duplicate keys exist, the last value wins.

_.object(['moe', 'larry', 'curly'], [30, 40, 50]);=> {moe: 30, larry: 40, curly: 50}_.object([['moe', 30], ['larry', 40], ['curly', 50]]);=> {moe: 30, larry: 40, curly: 50}

chunk_.chunk(array, length)source
Chunks anarray into multiple arrays, each containinglength or fewer items.

var partners = _.chunk(_.shuffle(kindergarten), 2);=> [["Tyrone", "Elie"], ["Aidan", "Sam"], ["Katrina", "Billie"], ["Little Timmy"]]

indexOf_.indexOf(array, value, [isSorted])source
Returns the index at whichvalue can be found in thearray, or-1 if value is not present in thearray. If you're working with a large array, and you know that the array is already sorted, passtrue forisSorted to use a faster binary search ... or, pass a number as the third argument in order to look for the first matching value in the array after the given index. IfisSorted istrue, this function uses operator< (note).

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

lastIndexOf_.lastIndexOf(array, value, [fromIndex])source
Returns the index of the last occurrence ofvalue in thearray, or-1 if value is not present. PassfromIndex to start your search at a given index.

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

sortedIndex_.sortedIndex(array, value, [iteratee], [context])source
Uses a binary search to determine the smallest index at which thevalueshould be inserted into thearray in order to maintain thearray's sorted order. If aniteratee function is provided, it will be used to compute the sort ranking of each value, including thevalue you pass. The iteratee may also be the string name of the property to sort by (eg.length). This function uses operator< (note).

_.sortedIndex([10, 20, 30, 40, 50], 35);=> 3var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}];_.sortedIndex(stooges, {name: 'larry', age: 50}, 'age');=> 1

findIndex_.findIndex(array, predicate, [context])source
Similar to_.indexOf, returns the first index where thepredicate truth test passes; otherwise returns-1.

_.findIndex([4, 6, 8, 12], isPrime);=> -1 // not found_.findIndex([4, 6, 7, 12], isPrime);=> 2

findLastIndex_.findLastIndex(array, predicate, [context])source
Like_.findIndex but iterates the array in reverse, returning the index closest to the end where thepredicate truth test passes.

var users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},             {'id': 2, 'name': 'Ted', 'last': 'White'},             {'id': 3, 'name': 'Frank', 'last': 'James'},             {'id': 4, 'name': 'Ted', 'last': 'Jones'}];_.findLastIndex(users, {  name: 'Ted'});=> 3

range_.range([start], stop, [step])source
A function to create flexibly-numbered lists of integers, handy foreach andmap loops.start, if omitted, defaults to0;step defaults to1 ifstart is beforestop, otherwise-1. Returns a list of integers fromstart (inclusive) tostop (exclusive), incremented (or decremented) bystep.

_.range(10);=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]_.range(1, 11);=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]_.range(0, 30, 5);=> [0, 5, 10, 15, 20, 25]_.range(0, -10, -1);=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]_.range(0);=> []

Function (uh, ahem) Functions

bind_.bind(function, object, *arguments)source
Bind afunction to anobject, meaning that whenever the function is called, the value ofthis will be theobject. Optionally, passarguments to thefunction to pre-fill them, also known aspartial application. For partial application without context binding, usepartial.

var func = function(greeting){ return greeting + ': ' + this.name };func = _.bind(func, {name: 'moe'}, 'hi');func();=> 'hi: moe'

bindAll_.bindAll(object, *methodNames)source
Binds a number of methods on theobject, specified bymethodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly uselessthis.methodNames are required.

var buttonView = {  label  : 'underscore',  onClick: function(){ alert('clicked: ' + this.label); },  onHover: function(){ console.log('hovering: ' + this.label); }};_.bindAll(buttonView, 'onClick', 'onHover');// When the button is clicked, this.label will have the correct value.jQuery('#underscore_button').on('click', buttonView.onClick);

partial_.partial(function, *arguments)source
Partially apply a function by filling in any number of itsarguments,without changing its dynamicthis value. A close cousin ofbind. You may pass_ in your list ofarguments to specify an argument that should not be pre-filled, but left open to supply at call-time.Note: if you need_ placeholders and athis binding at the same time, use both_.partial and_.bind.

var subtract = function(a, b) { return b - a; };sub5 = _.partial(subtract, 5);sub5(20);=> 15// Using a placeholdersubFrom20 = _.partial(subtract, _, 20);subFrom20(5);=> 15

memoize_.memoize(function, [hashFunction])source
Memoizes a givenfunction by caching the computed result. Useful for speeding up slow-running computations. If passed an optionalhashFunction, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The defaulthashFunction just uses the first argument to the memoized function as the key. The cache of memoized values is available as thecache property on the returned function.

var fibonacci = _.memoize(function(n) {  return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);});

delay_.delay(function, wait, *arguments)source
Much likesetTimeout, invokesfunction afterwait milliseconds. If you pass the optionalarguments, they will be forwarded on to thefunction when it is invoked.

var log = _.bind(console.log, console);_.delay(log, 1000, 'logged later');=> 'logged later' // Appears after one second.

defer_.defer(function, *arguments)source
Defers invoking thefunction until the current call stack has cleared, similar to usingsetTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating. If you pass the optionalarguments, they will be forwarded on to thefunction when it is invoked.

_.defer(function(){ alert('deferred'); });// Returns from the function before the alert runs.

throttle_.throttle(function, wait, [options])source
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per everywait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

By default,throttle will execute the function as soon as you call it for the first time, and, if you call it again any number of times during thewait period, as soon as that period is over. If you'd like to disable the leading-edge call, pass{leading: false}, and if you'd like to disable the execution on the trailing-edge, pass
{trailing: false}.

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

If you need to cancel a scheduled throttle, you can call.cancel() on the throttled function.

debounce_.debounce(function, wait, [immediate])source
Creates and returns a new debounced version of the passed function which will postpone its execution until afterwait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happenafter the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

At the end of thewait interval, the function will be called with the arguments that were passedmost recently to the debounced function.

Passtrue for theimmediate argument to causedebounce to trigger the function on the leading instead of the trailing edge of thewait interval. Useful in circumstances like preventing accidental double-clicks on a "submit" button from firing a second time.

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

If you need to cancel a scheduled debounce, you can call.cancel() on the debounced function.

once_.once(function)source
Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

var initialize = _.once(createApplication);initialize();initialize();// Application is only created once.

after_.after(count, function)source
Creates a wrapper offunction that does nothing at first. From thecount-th call onwards, it starts actually callingfunction. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

var renderNotes = _.after(notes.length, render);_.each(notes, function(note) {  note.asyncSave({success: renderNotes});});// renderNotes is run once, after all notes have saved.

before_.before(count, function)source
Creates a wrapper offunction that memoizes its return value. From thecount-th call onwards, the memoized result of the last invocation is returned immediately instead of invokingfunction again. So the wrapper will invokefunction at mostcount - 1 times.

var monthlyMeeting = _.before(3, askForRaise);monthlyMeeting();monthlyMeeting();monthlyMeeting();// the result of any subsequent calls is the same as the second call

wrap_.wrap(function, wrapper)source
Wraps the firstfunction inside of thewrapper function, passing it as the first argument. This allows thewrapper to execute code before and after thefunction runs, adjust the arguments, and execute it conditionally.

var hello = function(name) { return "hello: " + name; };hello = _.wrap(hello, function(func) {  return "before, " + func("moe") + ", after";});hello();=> 'before, hello: moe, after'

negate_.negate(predicate)source
Returns a new negated version of thepredicate function.

var isFalsy = _.negate(Boolean);_.find([-2, -1, 0, 1, 2], isFalsy);=> 0

compose_.compose(*functions)source
Returns the composition of a list offunctions, where each function consumes the return value of the function that follows. In math terms, composing the functionsf(),g(), andh() producesf(g(h())).

var greet    = function(name){ return "hi: " + name; };var exclaim  = function(statement){ return statement.toUpperCase() + "!"; };var welcome = _.compose(greet, exclaim);welcome('moe');=> 'hi: MOE!'

restArguments_.restArguments(function, [startIndex])source
Returns a version of thefunction that, when called, receives all arguments from and beyondstartIndex collected into a single array. If you don’t pass an explicitstartIndex, it will be determined by looking at the number of arguments to thefunction itself. Similar to ES6’srest parameters syntax.

var raceResults = _.restArguments(function(gold, silver, bronze, everyoneElse) {  _.each(everyoneElse, sendConsolations);});raceResults("Dopey", "Grumpy", "Happy", "Sneezy", "Bashful", "Sleepy", "Doc");

Object Functions

keys_.keys(object)source
Retrieve all the names of theobject's own enumerable properties.

_.keys({one: 1, two: 2, three: 3});=> ["one", "two", "three"]

allKeys_.allKeys(object)source
Retrieveall the names ofobject's own and inherited properties.

function Stooge(name) {  this.name = name;}Stooge.prototype.silly = true;_.allKeys(new Stooge("Moe"));=> ["name", "silly"]

values_.values(object)source
Return all of the values of theobject's own properties.

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

mapObject_.mapObject(object, iteratee, [context])source
Likemap, but for objects. Transform the value of each property in turn.

_.mapObject({start: 5, end: 12}, function(val, key) {  return val + 5;});=> {start: 10, end: 17}

pairs_.pairs(object)source
Convert an object into a list of[key, value] pairs. The opposite ofobject.

_.pairs({one: 1, two: 2, three: 3});=> [["one", 1], ["two", 2], ["three", 3]]

invert_.invert(object)source
Returns a copy of theobject where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.

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

create_.create(prototype, props)source
Creates a new object with the given prototype, optionally attachingprops asown properties. Basically,Object.create, but without all of the property descriptor jazz.

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

functions_.functions(object)Alias:methodssource
Returns a sorted list of the names of every method in an object — that is to say, the name of every function property of the object.

_.functions(_);=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...

findKey_.findKey(object, predicate, [context])source
Similar to_.findIndex but for keys in objects. Returns thekey where thepredicate truth test passes orundefined.predicate is transformed throughiteratee to facilitate shorthand syntaxes.

extend_.extend(destination, *sources)source
Shallowly copy all of the propertiesin thesource objects over to thedestination object, and return thedestination object. Any nested objects or arrays will be copied by reference, not duplicated. It's in-order, so the last source will override properties of the same name in previous arguments.

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

extendOwn_.extendOwn(destination, *sources)Alias:assignsource
Likeextend, but only copiesown properties over to the destination object.

pick_.pick(object, *keys)source
Return a copy of theobject, filtered to only have values for the allowedkeys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

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

omit_.omit(object, *keys)source
Return a copy of theobject, filtered to omit the disallowedkeys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.

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

defaults_.defaults(object, *defaults)source
Returnsobject after filling in itsundefined properties with the first value present in the following list ofdefaults objects.

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

clone_.clone(object)source
Create a shallow-copied clone of the providedplainobject. Any nested objects or arrays will be copied by reference, not duplicated.

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

tap_.tap(object, interceptor)source
Invokesinterceptor with theobject, and then returnsobject. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.

_.chain([1,2,3,200])  .filter(function(num) { return num % 2 == 0; })  .tap(alert)  .map(function(num) { return num * num })  .value();=> // [2, 200] (alerted)=> [4, 40000]

toPath_.toPath(path)source
Ensures thatpath is an array. Ifpath is a string, it is wrapped in a single-element array; if it is an array already, it is returned unmodified.

_.toPath('key');=> ['key']_.toPath(['a', 0, 'b']);=> ['a', 0, 'b'] // (same array)

_.toPath is used internally inhas,get,invoke,property,propertyOf andresult, as well as initeratee and all functions that depend on it, in order to normalize deep property paths. You can override_.toPath if you want to customize this behavior, for example to enable Lodash-like string path shorthands. Be advised that altering_.toPath will unavoidably cause some keys to become unreachable; override at your own risk.

// Support dotted path shorthands.var originalToPath = _.toPath;_.mixin({  toPath: function(path) {    return _.isString(path) ? path.split('.') : originalToPath(path);  }});_.get({a: [{b: 5}]}, 'a.0.b');=> 5

get_.get(object, path, [default])source
Returns the specified property ofobject.path may be specified as a simple key, or as an array of object keys or array indexes, for deep property fetching. If the property does not exist or isundefined, the optionaldefault is returned.

_.get({a: 10}, 'a');=> 10_.get({a: [{b: 2}]}, ['a', 0, 'b']);=> 2_.get({a: 10}, 'b', 100);=> 100

has_.has(object, key)source
Does the object contain the given key? Identical toobject.hasOwnProperty(key), but uses a safe reference to thehasOwnProperty function, in case it's beenoverridden accidentally.

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

property_.property(path)source
Returns a function that will return the specified property of any passed-in object.path may be specified as a simple key, or as an array of object keys or array indexes, for deep property fetching.

var stooge = {name: 'moe'};'moe' === _.property('name')(stooge);=> truevar stooges = {moe: {fears: {worst: 'Spiders'}}, curly: {fears: {worst: 'Moe'}}};var curlysWorstFear = _.property(['curly', 'fears', 'worst']);curlysWorstFear(stooges);=> 'Moe'

propertyOf_.propertyOf(object)source
Inverse of_.property. Takes an object and returns a function which will return the value of a provided property.

var stooge = {name: 'moe'};_.propertyOf(stooge)('name');=> 'moe'

matcher_.matcher(attrs)Alias:matchessource
Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present inattrs.

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

isEqual_.isEqual(object, other)source
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};var clone  = {name: 'moe', luckyNumbers: [13, 27, 34]};stooge == clone;=> false_.isEqual(stooge, clone);=> true

isMatch_.isMatch(object, properties)source
Tells you if the keys and values inproperties are contained inobject.

var stooge = {name: 'moe', age: 32};_.isMatch(stooge, {age: 32});=> true

isEmpty_.isEmpty(collection)source
Returnstrue ifcollection has no elements. For strings and array-like objects_.isEmpty checks if the length property is 0. For other objects, it returnstrue if the object has no enumerable own-properties. Note that primitive numbers, booleans and symbols are always empty by this definition.

_.isEmpty([1, 2, 3]);=> false_.isEmpty({});=> true

isElement_.isElement(object)source
Returnstrue ifobject is a DOM element.

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

isArray_.isArray(object)source
Returnstrue ifobject is an Array.

(function(){ return _.isArray(arguments); })();=> false_.isArray([1,2,3]);=> true

isObject_.isObject(value)source
Returnstrue ifvalue is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings and numbers are not.

_.isObject({});=> true_.isObject(1);=> false

isArguments_.isArguments(object)source
Returnstrue ifobject is an Arguments object.

(function(){ return _.isArguments(arguments); })(1, 2, 3);=> true_.isArguments([1,2,3]);=> false

isFunction_.isFunction(object)source
Returnstrue ifobject is a Function.

_.isFunction(alert);=> true

isString_.isString(object)source
Returnstrue ifobject is a String.

_.isString("moe");=> true

isNumber_.isNumber(object)source
Returnstrue ifobject is a Number (includingNaN).

_.isNumber(8.4 * 5);=> true

isFinite_.isFinite(object)source
Returnstrue ifobject is a finite Number.

_.isFinite(-101);=> true_.isFinite(-Infinity);=> false

isBoolean_.isBoolean(object)source
Returnstrue ifobject is eithertrue orfalse.

_.isBoolean(null);=> false

isDate_.isDate(object)source
Returnstrue ifobject is a Date.

_.isDate(new Date());=> true

isRegExp_.isRegExp(object)source
Returnstrue ifobject is a RegExp.

_.isRegExp(/moe/);=> true

isError_.isError(object)source
Returnstrue ifobject inherits from an Error.

try {  throw new TypeError("Example");} catch (o_O) {  _.isError(o_O);}=> true

isSymbol_.isSymbol(object)source
Returnstrue ifobject is aSymbol.

_.isSymbol(Symbol());=> true

isMap_.isMap(object)source
Returnstrue ifobject is aMap.

_.isMap(new Map());=> true

isWeakMap_.isWeakMap(object)source
Returnstrue ifobject is aWeakMap.

_.isWeakMap(new WeakMap());=> true

isSet_.isSet(object)source
Returnstrue ifobject is aSet.

_.isSet(new Set());=> true

isWeakSet_.isWeakSet(object)source
Returnstrue ifobject is aWeakSet.

_.isWeakSet(WeakSet());=> true

isArrayBuffer_.isArrayBuffer(object)source
Returnstrue ifobject is anArrayBuffer.

_.isArrayBuffer(new ArrayBuffer(8));=> true

isDataView_.isDataView(object)source
Returnstrue ifobject is aDataView.

_.isDataView(new DataView(new ArrayBuffer(8)));=> true

isTypedArray_.isTypedArray(object)source
Returnstrue ifobject is aTypedArray.

_.isTypedArray(new Int8Array(8));=> true

isNaN_.isNaN(object)source
Returnstrue ifobject isNaN.
Note: this is not the same as the nativeisNaN function, which will also return true for many other not-number values, such asundefined.

_.isNaN(NaN);=> trueisNaN(undefined);=> true_.isNaN(undefined);=> false

isNull_.isNull(object)source
Returnstrue if the value ofobject isnull.

_.isNull(null);=> true_.isNull(undefined);=> false

isUndefined_.isUndefined(value)source
Returnstrue ifvalue isundefined.

_.isUndefined(window.missingVariable);=> true

Utility Functions

noConflict_.noConflict()source
Give control of the global_ variable back to its previous owner. Returns a reference to theUnderscore object.

var underscore = _.noConflict();

The_.noConflict function is not present if you use the EcmaScript 6, AMD or CommonJS module system to import Underscore.

identity_.identity(value)source
Returns the same value that is used as the argument. In math:f(x) = x
This function looks useless, but is used throughout Underscore as a default iteratee.

var stooge = {name: 'moe'};stooge === _.identity(stooge);=> true

constant_.constant(value)source
Creates a function that returns the same value that is used as the argument of_.constant.

var stooge = {name: 'moe'};stooge === _.constant(stooge)();=> true

noop_.noop()source
Returnsundefined irrespective of the arguments passed to it. Useful as the default for optional callback arguments.

obj.initialize = _.noop;

times_.times(n, iteratee, [context])source
Invokes the given iteratee functionn times. Each invocation ofiteratee is called with anindex argument. Produces an array of the returned values.

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

random_.random(min, max)source
Returns a random integer betweenmin andmax, inclusive. If you only pass one argument, it will return a number between0 and that number.

_.random(0, 100);=> 42

mixin_.mixin(object)source
Allows you to extend Underscore with your own utility functions. Pass a hash of{name: function} definitions to have your functions added to the Underscore object, as well as the OOP wrapper. Returns the Underscore object to facilitate chaining.

_.mixin({  capitalize: function(string) {    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();  }});_("fabio").capitalize();=> "Fabio"

iteratee_.iteratee(value, [context])source
Generates a callback that can be applied to each element in a collection._.iteratee supports a number of shorthand syntaxes for common callback use cases. Depending uponvalue's type,_.iteratee will return:

// No value_.iteratee();=> _.identity()// Function_.iteratee(function(n) { return n * 2; });=> function(n) { return n * 2; }// Object_.iteratee({firstName: 'Chelsea'});=> _.matcher({firstName: 'Chelsea'});// Anything else_.iteratee('firstName');=> _.property('firstName');

The following Underscore methods transform their predicates through_.iteratee:countBy,every,filter,find,findIndex,findKey,findLastIndex,groupBy,indexBy,map,mapObject,max,min,partition,reject,some,sortBy,sortedIndex, anduniq

You may overwrite_.iteratee with your own custom function, if you want additional or different shorthand syntaxes:

// Support `RegExp` predicate shorthand.var builtinIteratee = _.iteratee;_.iteratee = function(value, context) {  if (_.isRegExp(value)) return function(obj) { return value.test(obj) };  return builtinIteratee(value, context);};

uniqueId_.uniqueId([prefix])source
Generate a globally-unique id for client-side models or DOM elements that need one. Ifprefix is passed, the id will be appended to it.

_.uniqueId('contact_');=> 'contact_104'

escape_.escape(string)source
Escapes a string for insertion into HTML, replacing&,<,>,",`, and' characters.

_.escape('Curly, Larry & Moe');=> "Curly, Larry &amp; Moe"

unescape_.unescape(string)source
The opposite ofescape, replaces&amp;,&lt;,&gt;,&quot;,&#x60; and&#x27; with their unescaped counterparts.

_.unescape('Curly, Larry &amp; Moe');=> "Curly, Larry & Moe"

result_.result(object, property, [defaultValue])source
If the value of the namedproperty is a function then invoke it with theobject as context; otherwise, return it. If a default value is provided and the property doesn't exist or is undefined then the default will be returned. IfdefaultValue is a function its result will be returned.

var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};_.result(object, 'cheese');=> "crumpets"_.result(object, 'stuff');=> "nonsense"_.result(object, 'meat', 'ham');=> "ham"

now_.now()source
Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions.

_.now();=> 1392066795351

template_.template(templateString, [settings])source
Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate values, using<%= … %>, as well as execute arbitrary JavaScript code, with<% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use<%- … %>. When you evaluate a template function, pass in adata object that has properties corresponding to the template's free variables. Thesettings argument should be a hash containing any_.templateSettings that should be overridden.

var compiled = _.template("hello: <%= name %>");compiled({name: 'moe'});=> "hello: moe"var template = _.template("<b><%- value %></b>");template({value: '<script>'});=> "<b>&lt;script&gt;</b>"

You can also useprint from within JavaScript code. This is sometimes more convenient than using<%= ... %>.

var compiled = _.template("<% print('Hello ' + epithet); %>");compiled({epithet: "stooge"});=> "Hello stooge"

If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define aninterpolate regex to match expressions that should be interpolated verbatim, anescape regex to match expressions that should be inserted after being HTML-escaped, and anevaluate regex to match expressions that should be evaluated without insertion into the resulting string. Note that if part of your template matches more than one of these regexes, the first will be applied by the following order of priority: (1)escape, (2)interpolate, (3)evaluate. You may define or omit any combination of the three. For example, to performMustache.js-style templating:

_.templateSettings = {  interpolate: /\{\{(.+?)\}\}/g};var template = _.template("Hello {{ name }}!");template({name: "Mustache"});=> "Hello Mustache!"

By default,template places the values from your data in the local scope via thewith statement. However, you can specify a single variable name with thevariable setting. This can significantly improve the speed at which a template is able to render.

_.template("Using 'with':<%= data.answer %>", {variable: 'data'})({answer: 'no'});=> "Using 'with': no"

Precompiling your templates can be a big help when debugging errors you can't reproduce. This is because precompiled templates can provide line numbers and a stack trace, something that is not possible when compiling templates on the client. Thesource property is available on the compiled template function for easy precompilation.

<script>  JST.project =<%= _.template(jstText).source %>;</script>

VERSION
It is possible to get the current Underscore version via_.VERSION .

_.VERSION => 1.13.7

Object-Oriented Style

You can use Underscore in either an object-oriented or a functional style, depending on your preference. The following two lines of code are identical ways to double a list of numbers.source,source

_.map([1, 2, 3], function(n){ return n * 2; });_([1, 2, 3]).map(function(n){ return n * 2; });

Chaining

Callingchain will cause all future method calls to return wrapped objects. When you've finished the computation, callvalue to retrieve the final value. Here's an example of chaining together amap/flatten/reduce, in order to get the word count of every word in a song.

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

In addition, theArray prototype's methods are proxied through the chained Underscore object, so you can slip areverse or apush into your chain, and continue to modify the array.

chain_.chain(obj)source
Returns a wrapped object. Calling methods on this object will continue to return wrapped objects untilvalue is called.

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

value_.chain(obj).value()source
Extracts the value of a wrapped object.

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

Links & Suggested Reading

Underscore.lua, a Lua port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (source)

Dollar.swift, a Swift port of many of the Underscore.js functions and more. (source)

Underscore.m, an Objective-C port of many of the Underscore.js functions, using a syntax that encourages chaining. (source)

_.m, an alternative Objective-C port that tries to stick a little closer to the original Underscore.js API. (source)

Underscore.php, a PHP port of the functions that are applicable in both languages. Tailored for PHP 5.4 and made with data-type tolerance in mind. (source)

Underscore-perl, a Perl port of many of the Underscore.js functions, aimed at on Perl hashes and arrays. (source)

Underscore.cfc, a Coldfusion port of many of the Underscore.js functions. (source)

Underscore.string, an Underscore extension that adds functions for string-manipulation:trim,startsWith,contains,capitalize,reverse,sprintf, and more.

Underscore-java, a java port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (source)

Ruby'sEnumerable module.

Prototype.js, which provides JavaScript with collection functions in the manner closest to Ruby's Enumerable.

Oliver Steele'sFunctional JavaScript, which includes comprehensive higher-order function support as well as string lambdas.

Michael Aufreiter'sData.js, a data manipulation + persistence library for JavaScript.

Python'sitertools.

PyToolz, a Python port that extends itertools and functools to include much of the Underscore API.

Funcy, a practical collection of functional helpers for Python, partially inspired by Underscore.

Notes

On the use of< in Underscore
Underscore functions that depend on ordering, such as_.sortBy and_.sortedIndex, use JavaScript’s built-inrelational operators, specifically the “less than” operator<. It is important to understand that these operators are only meaningful for numbers and strings. You can throw any value to them, but JavaScript will convert the operands to string or number first before performing the actual comparison. If you pass an operand that cannot be meaningfully converted to string or number, it ends up beingNaN by default. This value is unsortable.

Ideally, the values that you are sorting should either be all (meaningfully convertible to) strings or all (meaningfully convertible to) numbers. If this is not the case, you have two options:

Change Log

1.13.7July 24, 2024DiffDocs

1.13.6September 24, 2022DiffDocs
Hotfix for version 1.13.5 to remove apostinstall script from the package.json, which unexpectedly broke many people's builds.

1.13.5September 23, 2022DiffDocs

1.13.4June 2, 2022DiffDocs

1.13.3April 23, 2022DiffDocs

1.13.2December 16, 2021DiffDocs

1.13.1April 15, 2021DiffDocs

1.13.0April 9, 2021DiffDocs

1.13.0-3March 31, 2021DiffDocs

1.13.0-2March 15, 2021DiffDocs

1.12.1March 15, 2021DiffDocs

1.13.0-1March 11, 2021DiffDocs

1.13.0-0March 9, 2021DiffDocs

1.12.0November 24, 2020DiffDocs

1.11.0August 28, 2020DiffDocsArticle

1.10.2March 30, 2020DiffDocs

1.10.1March 30, 2020DiffDocs

1.10.0March 30, 2020DiffDocs

1.9.2Jan 6, 2020DiffDocs

1.9.1May 31, 2018DiffDocs

1.9.0April 18, 2018DiffDocs

1.8.3April 2, 2015DiffDocs

1.8.2Feb. 22, 2015DiffDocs

1.8.1Feb. 19, 2015DiffDocs

1.8.0Feb. 19, 2015DiffDocs

1.7.0August 26, 2014DiffDocs

1.6.0February 10, 2014DiffDocs

1.5.2September 7, 2013DiffDocs

1.5.1July 8, 2013DiffDocs

1.5.0July 6, 2013DiffDocs

1.4.4January 30, 2013DiffDocs

1.4.3December 4, 2012DiffDocs

1.4.2October 6, 2012DiffDocs

1.4.1October 1, 2012DiffDocs

1.4.0September 27, 2012DiffDocs

1.3.3April 10, 2012DiffDocs

1.3.1January 23, 2012DiffDocs

1.3.0January 11, 2012DiffDocs

1.2.4January 4, 2012DiffDocs

1.2.3December 7, 2011DiffDocs

1.2.2November 14, 2011DiffDocs

1.2.1October 24, 2011DiffDocs

1.2.0October 5, 2011DiffDocs

1.1.7July 13, 2011DiffDocs
Added_.groupBy, which aggregates a collection into groups of like items. Added_.union and_.difference, to complement the (re-named)_.intersection. Various improvements for support of sparse arrays._.toArray now returns a clone, if directly passed an array._.functions now also returns the names of functions that are present in the prototype chain.

1.1.6April 18, 2011DiffDocs
Added_.after, which will return a function that only runs after first being called a specified number of times._.invoke can now take a direct function reference._.every now requires an iterator function to be passed, which mirrors the ES5 API._.extend no longer copies keys when the value is undefined._.bind now errors when trying to bind an undefined value.

1.1.5March 20, 2011DiffDocs
Added an_.defaults function, for use merging together JS objects representing default options. Added an_.once function, for manufacturing functions that should only ever execute a single time._.bind now delegates to the native ES5 version, where available._.keys now throws an error when used on non-Object values, as in ES5. Fixed a bug with_.keys when used over sparse arrays.

1.1.4January 9, 2011DiffDocs
Improved compliance with ES5's Array methods when passingnull as a value._.wrap now correctly setsthis for the wrapped function._.indexOf now takes an optional flag for finding the insertion index in an array that is guaranteed to already be sorted. Avoiding the use of.callee, to allow_.isArray to work properly in ES5's strict mode.

1.1.3December 1, 2010DiffDocs
In CommonJS, Underscore may now be required with just:
var _ = require("underscore"). Added_.throttle and_.debounce functions. Removed_.breakLoop, in favor of an ES5-style un-break-able each implementation — this removes the try/catch, and you'll now have better stack traces for exceptions that are thrown within an Underscore iterator. Improved theisType family of functions for better interoperability with Internet Explorer host objects._.template now correctly escapes backslashes in templates. Improved_.reduce compatibility with the ES5 version: if you don't pass an initial value, the first item in the collection is used._.each no longer returns the iterated collection, for improved consistency with ES5'sforEach.

1.1.2October 15, 2010DiffDocs
Fixed_.contains, which was mistakenly pointing at_.intersect instead of_.include, like it should have been. Added_.unique as an alias for_.uniq.

1.1.1October 5, 2010DiffDocs
Improved the speed of_.template, and its handling of multiline interpolations. Ryan Tenney contributed optimizations to many Underscore functions. An annotated version of the source code is now available.

1.1.0August 18, 2010DiffDocs
The method signature of_.reduce has been changed to match the ES5 signature, instead of the Ruby/Prototype.js version. This is a backwards-incompatible change._.template may now be called with no arguments, and preserves whitespace._.contains is a new alias for_.include.

1.0.4June 22, 2010DiffDocs
Andri Möll contributed the_.memoize function, which can be used to speed up expensive repeated computations by caching the results.

1.0.3June 14, 2010DiffDocs
Patch that makes_.isEqual returnfalse if any property of the compared object has aNaN value. Technically the correct thing to do, but of questionable semantics. Watch out for NaN comparisons.

1.0.2March 23, 2010DiffDocs
Fixes_.isArguments in recent versions of Opera, which have arguments objects as real Arrays.

1.0.1March 19, 2010DiffDocs
Bugfix for_.isEqual, when comparing two objects with the same number of undefined keys, but with different names.

1.0.0March 18, 2010DiffDocs
Things have been stable for many months now, so Underscore is now considered to be out of beta, at1.0. Improvements since0.6 include_.isBoolean, and the ability to have_.extend take multiple source objects.

0.6.0February 24, 2010DiffDocs
Major release. Incorporates a number ofMile Frawley's refactors for safer duck-typing on collection functions, and cleaner internals. A new_.mixin method that allows you to extend Underscore with utility functions of your own. Added_.times, which works the same as in Ruby or Prototype.js. Native support for ES5'sArray.isArray, andObject.keys.

0.5.8January 28, 2010DiffDocs
Fixed Underscore's collection functions to work onNodeLists andHTMLCollections once more, thanks toJustin Tulloss.

0.5.7January 20, 2010DiffDocs
A safer implementation of_.isArguments, and a faster_.isNumber,
thanks toJed Schmidt.

0.5.6January 18, 2010DiffDocs
Customizable delimiters for_.template, contributed byNoah Sloan.

0.5.5January 9, 2010DiffDocs
Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object.

0.5.4January 5, 2010DiffDocs
Fix for multiple single quotes within a template string for_.template. See:Rick Strahl's blog post.

0.5.2January 1, 2010DiffDocs
New implementations ofisArray,isDate,isFunction,isNumber,isRegExp, andisString, thanks to a suggestion fromRobert Kieffer. Instead of doingObject#toString comparisons, they now check for expected properties, which is less safe, but more than an order of magnitude faster. Most other Underscore functions saw minor speed improvements as a result.Evgeniy Dolzhenko contributed_.tap,similar to Ruby 1.9's, which is handy for injecting side effects (like logging) into chained calls.

0.5.1December 9, 2009DiffDocs
Added an_.isArguments function. Lots of little safety checks and optimizations contributed byNoah Sloan andAndri Möll.

0.5.0December 7, 2009DiffDocs
[API Changes]_.bindAll now takes the context object as its first parameter. If no method names are passed, all of the context object's methods are bound to it, enabling chaining and easier binding._.functions now takes a single argument and returns the names of its Function properties. Calling_.functions(_) will get you the previous behavior. Added_.isRegExp so thatisEqual can now test for RegExp equality. All of the "is" functions have been shrunk down into a single definition.Karl Guertin contributed patches.

0.4.7December 6, 2009DiffDocs
AddedisDate,isNaN, andisNull, for completeness. Optimizations forisEqual when checking equality between Arrays or Dates._.keys is now25%–2X faster (depending on your browser) which speeds up the functions that rely on it, such as_.each.

0.4.6November 30, 2009DiffDocs
Added therange function, a port of thePython function of the same name, for generating flexibly-numbered lists of integers. Original patch contributed byKirill Ishanov.

0.4.5November 19, 2009DiffDocs
Addedrest for Arrays and arguments objects, and aliasedfirst ashead, andrest astail, thanks toLuke Sutton's patches. Added tests ensuring that all Underscore Array functions also work onarguments objects.

0.4.4November 18, 2009DiffDocs
AddedisString, andisNumber, for consistency. Fixed_.isEqual(NaN, NaN) to returntrue (which is debatable).

0.4.3November 9, 2009DiffDocs
Started using the nativeStopIteration object in browsers that support it. Fixed Underscore setup for CommonJS environments.

0.4.2November 9, 2009DiffDocs
Renamed the unwrapping function tovalue, for clarity.

0.4.1November 8, 2009DiffDocs
Chained Underscore objects now support the Array prototype methods, so that you can perform the full range of operations on a wrapped array without having to break your chain. Added abreakLoop method tobreak in the middle of any Underscore iteration. Added anisEmpty function that works on arrays and objects.

0.4.0November 7, 2009DiffDocs
All Underscore functions can now be called in an object-oriented style, like so:_([1, 2, 3]).map(...);. Original patch provided byMarc-André Cournoyer. Wrapped objects can be chained through multiple method invocations. Afunctions method was added, providing a sorted list of all the functions in Underscore.

0.3.3October 31, 2009DiffDocs
Added the JavaScript 1.8 functionreduceRight. Aliased it asfoldr, and aliasedreduce asfoldl.

0.3.2October 29, 2009DiffDocs
Now runs on stockRhino interpreters with:load("underscore.js"). Addedidentity as a utility function.

0.3.1October 29, 2009DiffDocs
All iterators are now passed in the original collection as their third argument, the same as JavaScript 1.6'sforEach. Iterating over objects is now called with(value, key, collection), for details see_.each.

0.3.0October 29, 2009DiffDocs
AddedDmitry Baranovskiy's comprehensive optimizations, merged inKris Kowal's patches to make UnderscoreCommonJS andNarwhal compliant.

0.2.0October 28, 2009DiffDocs
Addedcompose andlastIndexOf, renamedinject toreduce, added aliases forinject,filter,every,some, andforEach.

0.1.1October 28, 2009DiffDocs
AddednoConflict, so that the "Underscore" object can be assigned to other variables.

0.1.0October 28, 2009Docs
Initial release of Underscore.js.

A DocumentCloud Project


[8]ページ先頭

©2009-2025 Movatter.jp