Overview
Underscore.js is a very lean library, with only 4KB compression. It provides dozens of functional programming methods, which greatly facilitates Javascript programming. The MVC framework backbone.js is based on this library.
It defines an underscore (_) object, and all methods of the function library belong to this object. These methods can be roughly divided into five categories: collection, array, function, object and utility.
Install under node.js
Underscore.js can be used not only in browser environments, but also in node.js. The installation command is as follows:
The code copy is as follows:
npm install underscore
However, node.js cannot use _ directly as a variable name, so you need to use underscore.js using the following method.
The code copy is as follows:
var u = require("underscore");
Methods related to collections
A data collection of Javascript language, including two structures: arrays and objects. The following method applies to both structures.
map
This method performs some operation on each member of the collection in turn, and stores the returned values into a new array in turn.
The code copy is as follows:
_.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]
Each
This method is similar to map, performing some operation on each member of the set in sequence, but does not return a value.
The code copy is as follows:
_.each([1, 2, 3], alert); _.each({one : 1, two : 2, three : 3}, alert);
Reduce
This method performs some operation on each member of the set in sequence, and then accumulates the operation results on a certain initial value. After all operations are completed, the accumulated value is returned.
This method accepts three parameters. The first parameter is the set to be processed, the second parameter is the function that operates on each member, and the third parameter is the variable used to accumulate.
_.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0); // 6
The second parameter of the reduce method is the operation function, which itself accepts two parameters. The first is the variable used to accumulate, and the second is the value of each member of the set.
filter and reject
The filter method performs some operation on each member of the collection in turn, and only returns members whose operation result is true.
The code copy is as follows:
_.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); // [2, 4, 6]
The reject method only returns members whose operation result is false.
The code copy is as follows:
_.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); // [1, 3, 5]
Every and some
The every method performs some operation on each member of the collection in turn. If the operation result of all members is true, it returns true, otherwise it returns false.
The code copy is as follows:
_.every([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); // false
Some method returns true as long as there is a member's operation result, otherwise false.
The code copy is as follows:
_.some([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); // true
Find
This method performs some operation on each member of the set in sequence, returning the member whose first operation result is true. If the operation result of all members is false, undefined is returned.
The code copy is as follows:
_.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); // 2
contains
If a value is within the set, the method returns true, otherwise it returns false.
The code copy is as follows:
_.contains([1, 2, 3], 3); // true
countBy
This method performs some operation on each member of the set in sequence, counts members with the same operation result as a class, and finally returns an object, indicating the number of members corresponding to each operation result.
The code copy is as follows:
_.countBy([1, 2, 3, 4, 5], function(num) { return num % 2 == 0 ? 'even' : 'odd'; }); // {odd: 3, even: 2}
shuffle
This method returns a collection of disordered order.
The code copy is as follows:
_.shuffle([1, 2, 3, 4, 5, 6]); // [4, 1, 6, 3, 5, 2]
size
This method returns the number of members of the collection.
The code copy is as follows:
_.size({one : 1, two : 2, three : 3}); // 3
Object-related methods
toArray
This method converts the object into an array.
The code copy is as follows:
_.toArray({a:0,b:1,c:2}); // [0, 1, 2]
pluck
This method extracts the value of a property of multiple objects into an array.
The code copy is as follows:
var standes = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.pluck(stooges, 'name'); // ["moe", "larry", "curly"]
Methods related to functions
bind
This method binds the context of the function runtime and returns as a new function.
The code copy is as follows:
_.bind(function, object, [*arguments])
Please see the example below.
The code copy is as follows:
var o = { p: 2, m: function (){console.log(p);} }; om() // 2 _.bind(om,{p:1})() // 1
bindAll
This method binds all methods of an object (unless otherwise specified) to that object.
The code copy is as follows:
var buttonView = { label : 'underscore', onClick : function(){ alert('clicked: ' + this.label); }, onHover : function(){ console.log('hovering: ' + this.label); } }; _.bindAll(buttonView);
partial
This method binding binds a function to a parameter and returns as a new function.
The code copy is as follows:
var add = function(a, b) { return a + b; }; add5 = _.partial(add, 5); add5(10); // 15
memoize
This method caches the running results of a function for a parameter.
The code copy is as follows:
var fibonacci = _.memoize(function(n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); });
If a function has multiple parameters, a hashFunction needs to be provided to generate a hash value that identifies the cache.
delay
This method can delay the function for a specified time before running.
The code copy is as follows:
var log = _.bind(console.log, console); _.delay(log, 1000, 'logged later'); // 'logged later'
defer
This method can postpone the function until the number of tasks to be run is 0 before running, similar to the effect of setTimeout delaying the run by 0 seconds.
The code copy is as follows:
_.defer(function(){ alert('deferred'); });
throttle
This method returns a new version of a function. When calling this new version of the function continuously, you must wait for a certain period of time before the next execution will be triggered.
The code copy is as follows:
// Return the new version of the updatePosition function var throttled = _.throttle(updatePosition, 100); // The new version of the function will only trigger $(window).scroll(throttled);
Debounce
This method also returns a new version of a function. Each time this new version of the function is called, it must be a certain time interval from the last call, otherwise it will be invalid. Its typical application is to prevent the user from double-clicking a button, resulting in two forms submissions.
The code copy is as follows:
$("button").on("click", _.debounce(submitForm, 1000));
once
This method returns a new version of the function so that the function can only be run once. Mainly used for object initialization.
The code copy is as follows:
var initialize = _.once(createApplication); initialize(); initialize(); // Application is created only once
After
This method returns a new version of the function, which will only be run after being called a certain number of times. It is mainly used to confirm that a set of operations is completed before reacting.
The code copy is as follows:
var renderNotes = _.after(notes.length, render); _.each(notes, function(note) { note.asyncSave({success: renderNotes}); }); // All notes are saved, renderNote will run once
wrap
This method passes one function as a parameter into another function, and finally returns a new version of the former.
The code copy is as follows:
var hello = function(name) { return "hello: " + name; }; hello = _.wrap(hello, function(func) { return "before, " + func("moe") + ", after"; }); hello(); // 'before, hello: moe, after'
compose
This method accepts a series of functions as parameters, runs from back to forward, and the running result of the previous function is used as the running parameter of the next function. That is to say, convert the form of f(g(),h()) into f(g(h())).
The code copy is as follows:
var greet = function(name){ return "hi: " + name; }; var excem = function(statement){ return statement + "!"; }; var welcome = _.compose(exclaim, greet); welcome('moe'); // 'hi: moe!'
Tools and methods
template
This method is used to compile HTML templates. It accepts three parameters.
The code copy is as follows:
_.template(templateString, [data], [settings])
The meanings of the three parameters are as follows:
templateString: template string
data: Enter the data of the template
settings: Settings
templateString
The template string templateString is an ordinary HTML language, where variables are inserted in the form of <%= … %>; the data object is responsible for providing the value of the variable.
The code copy is as follows:
var txt = "
<%= word %>
The code copy is as follows:
"; _.template(txt, {word : "Hello World"}) // "
Hello World
The code copy is as follows:
"
If the value of a variable contains five special characters (& < > ” ' /), it needs to be escaped with <%- … %>.
The code copy is as follows:
var txt = "
<%- word %>
The code copy is as follows:
"; _.template(txt, {word : "H & W"}) //
H & W
JavaScript commands can be inserted in the form of <% … %>. Below is an example of a judgment statement.
The code copy is as follows:
var txt = "<% var i = 0; if (i<1){ %>" + "<%= word %>" + "<% } %>"; _.template(txt, {word : "Hello World"}) // Hello World
Common usages include loop statements.
The code copy is as follows:
var list = "<% _.each(people, function(name) { %>
<%= name %> <% }); %>"; _.template(list, {people : ['moe', 'curly', 'larry']}); // "
moe
curly
larry”
If the template method has only the first parameter templateString and the second parameter is omitted, then a function will be returned, and data can be input to this function in the future.
The code copy is as follows:
var t1 = _.template("Hello <%=user%>!"); t1({ user: "" }) // 'Hello !'
data
All variables in templateString are internally attributes of the obj object, and the obj object refers to the second parameter data object. The following two sentences are equivalent.
The code copy is as follows:
_.template("Hello <%=user%>!", { user: "" }) _.template("Hello <%=obj.user%>!", { user: "" })
If you want to change the name of the obj object, you need to set it in the third parameter.
The code copy is as follows:
_.template("<%if (data.title) { %>Title: <%= title %><% } %>", null, { variable: "data" });
Because template uses with statements internally when replacing variables, the above method will run faster.