Home > Web Front-end > JS Tutorial > Summary of common methods of Underscore.js_Others

Summary of common methods of Underscore.js_Others

WBOY
Release: 2016-05-16 16:12:12
Original
1259 people have browsed it

Overview

Underscore.js is a very lean library, only 4KB compressed. 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:

Copy code The code is as follows:

npm install underscore

However, node.js cannot directly use _ as a variable name, so use underscore.js in the following method.
Copy code The code is as follows:

var u = require("underscore");

Methods related to collections

Javascript language data collection includes two structures: arrays and objects. The following methods apply to both structures.

map

This method performs some operation on each member of the collection in turn, and stores the returned value in a new array.

Copy code The 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

This method is similar to map, which performs some operation on each member of the collection in turn, but does not return a value.

Copy code The code is as follows:

_.each([1, 2, 3], alert); _.each({one : 1, two : 2, three : 3}, alert);

reduce

This method performs some kind of operation on each member of the set in turn, 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 collection being processed, the second parameter is the function that operates on each member, and the third parameter is the variable used for accumulation.

_.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 for accumulation, 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.

Copy code The code 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.
Copy code The 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 some operation on each member of the collection in turn. If the operation results of all members are true, it returns true, otherwise it returns false.

Copy code The code is as follows:

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

Some methods return true as long as the operation result of one member is true, otherwise it returns false.
Copy code The code 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 collection in turn and returns the first member whose operation result is true. If the operation result of all members is false, undefined is returned.

Copy code The 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 collection, this method returns true, otherwise it returns false.

Copy code The code is as follows:

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

countBy

This method performs some kind of operation on each member of the set in turn, counts members with the same operation results as one category, and finally returns an object indicating the number of members corresponding to each operation result.

Copy code The 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 shuffled collection.

Copy code The 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 collection.

Copy code The code is as follows:

_.size({one : 1, two : 2, three : 3}); // 3

Methods related to objects


toArray

This method converts the object into an array.

Copy code The code is as follows:

_.toArray({a:0,b:1,c:2}); // [0, 1, 2]

pluck

This method extracts the value of a certain attribute of multiple objects into an array.

Copy code The code is as follows:

var stooges = [{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 function runtime context and returns it as a new function.

Copy code The code is as follows:

_.bind(function, object, [*arguments])

Please see the example below.
Copy code The 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 of an object (unless specifically stated) to the object.

Copy code The 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 binding binds a function to parameters and then returns it as a new function.

Copy code The 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 certain parameter.

Copy code The code 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 postpone the function to run for a specified time.

Copy code The code is as follows:

var log = _.bind(console.log, console); _.delay(log, 1000, 'logged later'); // 'logged later'

defer

This method can postpone running the function until the number of tasks to be run reaches 0, similar to the effect of setTimeout delaying running for 0 seconds.

Copy code The code is as follows:

_.defer(function(){ alert('deferred'); });

throttle

This method returns a new version of the function. When calling this new version of the function continuously, you must wait for a certain period of time before triggering the next execution.

Copy code The code is as follows:

// Return the new version of the updatePosition function var throttled = _.throttle(updatePosition, 100); // The new version of the function will only be triggered every 100 milliseconds $(window).scroll(throttled);

debounce

This method also returns a new version of a function. Each time this new version of the function is called, there must be a certain amount of time between the previous call, otherwise it will be invalid. Its typical application is to prevent users from double-clicking a button, causing the form to be submitted twice.

Copy code The code is as follows:

$("button").on("click", _.debounce(submitForm, 1000));

once

This method returns a new version of the function so that this function can only be run once. Mainly used for object initialization.

Copy code The code is as follows:

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

after

This method returns a new version of the function. This function will only run after being called a certain number of times. It is mainly used to confirm that a set of operations are completed before reacting.

Copy code The code is as follows:

var renderNotes = _.after(notes.length, render); _.each(notes, function(note) { note.asyncSave({success: renderNotes}); }); // After all notes are saved, renderNote It will only run once

wrap

This method takes a function as a parameter, passes it into another function, and finally returns a new version of the former.

Copy code The 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 and runs them in sequence from back to front. The running result of the previous function is used as the running parameter of the next function. In other words, convert the form of f(g(),h()) into f(g(h())).

Copy code The 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 code The code is as follows:

_.template(templateString, [data], [settings])

The meanings of the three parameters are as follows:

templateString: template string
data: input template data
settings: settings

templateString

The template string templateString is an ordinary HTML language, in which variables are inserted in the form of <%= ... %>; the data object is responsible for providing the value of the variable.

Copy code The code is as follows:

var txt = "

<%= word %>

Copy code The code is as follows:

"; _.template(txt, {word : "Hello World"}) // "

Hello World

Copy code The code is as follows:

"

If the value of the variable contains five special characters (& < > ” ‘ /), it needs to be escaped with <%- … %>.
Copy code The code is as follows:

var txt = "

<%- word %>
Copy code The code is as follows:

"; _.template(txt, {word : "H & W"}) //

H & W

JavaScript commands can be inserted in the form of <% … %>. The following is an example of a judgment statement.

Copy code The code is as follows:

var txt = "<% var i = 0; if (i<1){ %>" "<%= word %>" "<% } %>"; _.template(txt, { word : "Hello World"}) // Hello World

Common usages include loop statements.
Copy code The 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 omits the second parameter, a function will be returned, and data can be input to this function in the future.
Copy code The code 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 statements are equivalent.

Copy code The code 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.
Copy code The code is as follows:

_.template("<%if (data.title) { %>Title: <%= title %><% } %>", null,        { variable: "data" });

Because template uses the with statement internally when replacing variables, the above approach will run faster.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template