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

Summary of common methods of Underscore.js_Others

May 16, 2016 pm 04:12 PM
Common methods

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.
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

See all articles