Summary of common Underscore. js methods and summary of underscore. js

Source: Internet
Author: User

Summary of common Underscore. js methods and summary of underscore. js

Overview

Underscore. js is a very lean library, which is only 4 kb after compression. It provides dozens of functional programming methods, greatly facilitating Javascript programming. The MVC Framework backbone. js is based on this library.

It defines an underscore (_) object. All methods of the function library belong to this object. These methods can be divided into five categories: collection, array, function, object, and utility.

Install it in node. js

Underscore. js can be used not only in the browser environment, but also in node. js. The installation command is as follows:
Copy codeThe Code is as follows:
Npm install underscore

However, node. js cannot directly use _ as the variable name. Therefore, use underscore. js in the following method.
Copy codeThe Code is as follows:
Var u = require ("underscore ");

Set-related methods

A collection of Javascript data, including arrays and objects. The following method applies to both structures.

Map

This method performs some operations on each member of the Set, and stores the returned values in a new array in sequence.
Copy codeThe Code 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

Similar to map, this method performs some operations on each member of the Set in sequence, but does not return values.
Copy codeThe Code is as follows:
_. Each ([1, 2, 3], alert); _. each ({one: 1, two: 2, three: 3}, alert );

Reduce

This method performs an operation on each member of the Set in sequence, and accumulates the operation result on an initial value. After all the 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 to operate on each member, and the third parameter is the accumulative variable.

_. 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 accumulative variable, and the second is the value of each member in the set.

Filter and reject

The filter method performs an operation on each member of the Set in sequence, and returns only members whose operation result is true.
Copy codeThe Code is as follows:
_. Filter ([1, 2, 3, 4, 5, 6], function (num) {return num % 2 = 0 ;}); // [2, 4, 6]

The reject method returns only members whose operation result is false.
Copy codeThe Code 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 an operation on each member of the Set in sequence. If the operation result of all members is true, true is returned. Otherwise, false is returned.
Copy codeThe Code is as follows:
_. Every ([1, 2, 3, 4, 5, 6], function (num) {return num % 2 = 0 ;}); // false

Some method returns true if the operation result of one member is true. Otherwise, false is returned.
Copy codeThe Code is as follows:
_. Some ([1, 2, 3, 4, 5, 6], function (num) {return num % 2 = 0 ;}); // true

Find

This method performs an operation on each member of the Set in sequence, and returns the first member with the true operation result. If the operation result of all members is false, undefined is returned.
Copy codeThe Code is as follows:
_. Find ([1, 2, 3, 4, 5, 6], function (num) {return num % 2 = 0 ;}); // 2

Contains

If a value is in the Set, this method returns true; otherwise, false.
Copy codeThe Code is as follows:
_. Contains ([1, 2, 3], 3); // true

CountBy

This method performs an operation on each member of the Set in sequence, counts the members with the same operation results as one type, and returns an object, indicating the number of Members corresponding to each operation result.
Copy codeThe Code 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 disordered set.
Copy codeThe Code 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 set.
Copy codeThe Code is as follows:
_. Size ({one: 1, two: 2, three: 3}); // 3

Object-related methods


ToArray

This method converts an object into an array.
Copy codeThe Code is as follows:
_. ToArray ({a: 0, B: 1, c: 2}); // [0, 1, 2]

Pluck

This method extracts the values of one attribute of multiple objects into an array.
Copy codeThe Code is as follows:
Var stooges = [{name: 'moe', age: 40}, {name: 'Larry ', age: 50}, {name: 'curly', age: 60}]; _. pluck (stooges, 'name'); // ["moe", "larry", "curly"]

Function-related methods

Bind

This method binds the context of the function runtime and is returned as a new function.
Copy codeThe Code is as follows:
_. Bind (function, object, [* arguments])

See the following example.
Copy codeThe Code is as follows:
Var o = {p: 2, m: function () {console. log (p) ;}}; o. m () // 2 _. bind (o. m, {p: 1}) () // 1

BindAll

This method binds all methods (unless otherwise stated) of an object to this object.
Copy codeThe Code 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 binds a function to a parameter and returns it as a new function.
Copy codeThe Code 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 specific parameter.
Copy codeThe Code is as follows:
Var maid (function (n) {return n <2? N: Maid (n-1) + maid (n-2 );});

If a function has multiple parameters, a hashFunction must be provided to generate a hash value that identifies the cache.

Delay

This method can delay the function for a specified time before running.
Copy codeThe Code is as follows:
Var log = _. bind (console. log, console); _. delay (log, 1000, 'logging later'); // 'logging later'

Defer

This method can delay the function until the number of tasks to be run is 0, similar to the effect that setTimeout delays running for 0 seconds.
Copy codeThe Code is as follows:
_. Defer (function () {alert ('referred ');});

Throttle

This method returns a new version of a function. When calling this new function continuously, you must wait for a certain amount of time to trigger the next execution.
Copy codeThe Code is as follows:
// Return the new version of the updatePosition function var throttled = _. throttle (updatePosition, 100); // The new function is triggered every 100 milliseconds $ (window ). scroll (throttled );

Debounce

This method also returns a new version of a function. Each time you call this new function, it must be separated from the previous call for a certain period of time, otherwise it will be invalid. Its typical application is to prevent users from double-clicking a button, resulting in two forms being submitted.
Copy codeThe Code is as follows:
$ ("Button"). on ("click", _. debounce (submitForm, 1000 ));

Once

This method returns a new function version so that the function can only be run once. It is mainly used for object initialization.
Copy codeThe Code is as follows:
Var initialize = _. once (createApplication); initialize (); // The Application is created only once.

After

This method returns a new function that runs only after being called for a certain number of times. It is mainly used to confirm that a group of operations are completed before responding.
Copy codeThe Code is as follows:
Var renderNotes = _. after (notes. length, render );_. each (notes, function (note) {note. asyncSave ({success: renderNotes}) ;}); // after all the notes are saved, renderNote will run once.

Wrap

This method uses a function as a parameter, passes in another function, and finally returns a new version of the former.
Copy codeThe Code 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, which are run in sequence from the back to the back. 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 () to f (g (h ())).
Copy codeThe Code is as follows:
Var greet = function (name) {return "hi:" + name ;}; var exclaim = function (statement) {return statement + "! ";}; Var welcome = _. compose (exclaim, greet); welcome ('moe'); // 'Hi: moe! '

Tool Methods

Template

This method is used to compile HTML templates. It accepts three parameters.
Copy codeThe Code is as follows:
_. Template (templateString, [data], [settings])

The meanings of the three parameters are as follows:

TemplateString: Template string
Data: data of the input template
Settings: settings
 

TemplateString

The template string templateString is a common HTML language, where the variables use <% =... The data object is responsible for providing the value of the variable.
Copy codeThe Code is as follows:
Var txt ="

<% = Word %>
Copy codeThe Code is as follows:
"; _. Template (txt, {word:" Hello World "})//"

Hello World

Copy codeThe Code is as follows:
"

<% -... %> Escape.
Copy codeThe Code is as follows:
Var txt ="

<%-Word %>
Copy codeThe Code is as follows:
"; _. Template (txt, {word:" H & W "})//

H & W

JavaScript commands can use <%... %>. The following is an example of a judgment statement.
Copy codeThe Code is as follows:
Var txt = "<% var I = 0; if (I <1) {%>" + "<% = word %>" + "<%} %> "; _. template (txt, {word: "Hello World"}) // Hello World

The common usage is loop statements.
Copy codeThe Code is as follows:
Var list = "<% _. each (people, function (name) {%>

<% = Name %> <%}); %> ";_. template (list, {people: ['moe', 'curly ', 'Larry']}); //"
Moe
Curly
Larry"
If the template method only has the first parameter templateString and the second parameter is omitted, a function is returned and data can be input to the function later.
Copy codeThe Code is as follows:
Var t1 = _. template ("Hello <% = user %>! "); T1 ({user:" "}) // 'Hello! '

Data

All variables in templateString are internal properties of the obj object, and the obj object is the second parameter data object. The following two statements are equivalent.
Copy codeThe Code is as follows:
_. Template ("Hello <% = user %>! ", {User:" "}) _. template (" Hello <% = obj. user %>! ", {User :""})

If you want to change the Object Name of obj, you must set it in the third parameter.
Copy codeThe Code is as follows:
_. Template ("<% if (data. title) {%> Title: <% = title %> <%} %> ", null, {variable:" data "});

Because the with statement is used internally when the template is replaced with a variable, the above method runs faster.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.