亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Get to know Underscore.js
Practical application of underline
Great, but do I really need this?
start using
Functional or object-oriented?
Check function
gather
pick
map
全部
數(shù)組
Uniq
范圍
交叉路口
對(duì)象
鍵和值
默認(rèn)值
函數(shù)
綁定
實(shí)用程序
模板化
仍然不相信你應(yīng)該選擇這個(gè)
Home CMS Tutorial WordPress Embrace the warmth of Underscore.js

Embrace the warmth of Underscore.js

Aug 28, 2023 pm 02:53 PM

擁抱 Underscore.js 的溫暖

As JavaScript slowly moves out of browsers, there are tools that can significantly improve the robustness of JavaScript.

One of the tools is called Underscore.js, and that’s the tool we’re going to introduce today. let's start!


Get to know Underscore.js

So what exactly does Underscore do?

Underscore is a JavaScript utility library that provides much of the functional programming support you'd expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.

塊引用>

One of the benefits of working in Python or Ruby is the fancy constructs like map that make life so much easier. Unfortunately, the current version of JavaScript is quite crude in terms of low-level utilities.

As you read above, Underscore.js is a beautiful little JavaScript library that brings an incredible amount of functionality to the table at just 4kb.


Practical application of underline

“Enough nonsense about libraries,” I can hear you say. you are right! Before I continue my rant, let's see Underscore in action.

Suppose you have a random set of test scores, and you want a list containing the 90 scores. You would typically write something like this:

var scores = [84, 99, 91, 65, 87, 55, 72, 68, 95, 42], 
topScorers = [], scoreLimit = 90;

for (i=0; i<=scores.length; i++)
{
	if (scores[i]>scoreLimit)
	{
		topScorers.push(scores[i]);
	}
}

console.log(topScorers);

It's very simple, and even with optimizations, quite verbose for what we want to do.

Let’s see what we can achieve next with Underscore.


var scores = [84, 99, 91, 65, 87, 55, 72, 68, 95, 42], 
topScorers = [], scoreLimit = 90;

topScorers = _.select(scores, function(score){ return score > scoreLimit;});

console.log(topScorers);

I don’t know about you, but I’m just kind of nerdy. This is some incredibly concise and readable code.


Great, but do I really need this?

Well, it all depends on what you want to do. If your use of JavaScript is limited to playing with the DOM, the answer is mostly no, since jQuery can do most of what you want to do.

Yes.

On the other hand, if you are dealing with non-DOM code or even complex code, think MVC, front-end code, Underscore is definitely a boon.

While some of the functionality exposed by this library is slowly making its way into the ECMA specification, it's not available in all browsers, and getting your code to work across browsers is another nightmare in itself. Underscore gives you a nice set of abstractions that can be used anywhere.

If you are a performance-oriented person (and you should be), Underscore will fall back to the native implementation (if available) to ensure the best possible performance.


start using

Just grab the source code here and include it in your page.

If you are expecting a large setup process, you will be sorely disappointed. Just grab the source code here and include it in your page.

Underscore is created globally through a single object and exposes all its functionality. The object is the title underscore character _.

In case you were wondering, yes, this is very similar to how jQuery uses the dollar [$] sign. Just like jQuery, you can remap this character in case you encounter conflicts. Or if you’re like me and have an irrational love for the tilde.


Functional or object-oriented?

While the library's official marketing claim claims that it adds functional programming support, there's actually another way of doing things.

Let’s take the previous code as an example:


var scores = [84, 99, 91, 65, 87, 55, 72, 68, 95, 42], topScorers = [], scoreLimit = 90;

topScorers = _.select(scores, function(score){ return score > scoreLimit;});

console.log(topScorers);

The above methods are functional or procedural methods. You can also use a more direct and perhaps more obvious object-oriented approach.


var scores = [84, 99, 91, 65, 87, 55, 72, 68, 95, 42], topScorers = [], scoreLimit = 90;

topScorers = _(scores).select(function(score){ return score > scoreLimit;});

console.log(topScorers);

There's no real "right" way to do things, but keep in mind that you can chain jQuery-style methods using the latter approach.


Check function

Underscore provides more than 60 functions covering a variety of functions. Essentially, they can be divided into groups of functions, which run on:

  • collect
  • Array
  • Object
  • function
  • Utilities

Let's look at what each section does, and if applicable, my favorite one or two from each section.


gather

A collection can be an array or an object, or if I'm semantically correct, an associative array in JavaScript.

Underscore provides many methods to operate on collections. We saw the select method earlier. Here are some more very useful ones.

pick

Suppose you have a nice little array of key-value pairs, and you want to extract a specific property from each array. With Underscore, it's a breeze.


var Tuts = [{name : 'NetTuts', niche : 'Web Development'}, {name : 'WPTuts', niche : 'WordPress'}, {name : 'PSDTuts', niche : 'PhotoShop'}, {name : 'AeTuts', niche : 'After Effects'}];
var niches = _.pluck(Tuts, 'niche');

console.log(niches);

// ["Web Development", "WordPress", "PhotoShop", "After Effects"]

Using pluck is as simple as passing in the target object or array and selecting which property. Here I just extract the niche of each website.

map

Map creates an array from a collection where each element can be mutated or otherwise changed by a function.

讓我們以前面的示例為例并對(duì)其進(jìn)行一些擴(kuò)展。


var Tuts = [{name : 'NetTuts', niche : 'Web Development'}, {name : 'WPTuts', niche : 'WordPress'}, {name : 'PSDTuts', niche : 'PhotoShop'}, {name : 'AeTuts', niche : 'After Effects'}];

var names = _(Tuts).pluck('name').map(function (value){return value + '+'});

console.log(names);

// ["NetTuts+", "WPTuts+", "PSDTuts+", "AeTuts+"]

由于我注意到名稱末尾缺少加號(hào),因此我將它們添加到提取的數(shù)組中。

這里您不僅限于簡(jiǎn)單的串聯(lián)。您可以根據(jù)自己的意愿隨意修改傳遞的值。

全部

all 如果您需要檢查集合中的每個(gè)值是否滿足特定條件,則非常有用。例如,檢查學(xué)生是否通過了每個(gè)科目。


var Scores = [95, 82, 98, 78, 65];
var hasPassed = _(Scores).all(function (value){return value>50; });

console.log(hasPassed);

// true

數(shù)組

Underscore 有很多專門處理數(shù)組的函數(shù),這是非常受歡迎的,因?yàn)榕c其他語(yǔ)言相比,JavaScript 提供的處理數(shù)組的方法非常少。

Uniq

此方法基本上解析數(shù)組并刪除所有重復(fù)元素,只為您提供唯一元素。


var uniqTest = _.uniq([1,5,4,4,5,2,1,1,3,2,2,3,4,1]);

console.log(uniqTest);

// [1, 5, 4, 2, 3]

當(dāng)您解析巨大的數(shù)據(jù)集并需要清除重復(fù)項(xiàng)時(shí),這非常方便。請(qǐng)記住,僅計(jì)算元素的第一個(gè)實(shí)例,因此保留原始順序。

范圍

一種非常方便的方法,可讓您創(chuàng)建“范圍”或數(shù)字列表。讓我們看一個(gè)超級(jí)簡(jiǎn)單的例子。


var tens = _.range(0, 100, 10);

console.log(tens);

// [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

該方法的參數(shù)依次為起始值、結(jié)束值和步長(zhǎng)值。如果您想知道,使用負(fù)步長(zhǎng)值會(huì)導(dǎo)致遞減范圍。

交叉路口

此方法將兩個(gè)數(shù)組相互比較,并返回在所有傳遞的數(shù)組中找到的元素列表,即集合論中的交集。

讓我們擴(kuò)展前面的示例來看看它是如何工作的。


var tens = _.range(0, 100, 10), eights = _.range(0, 100, 8), fives = _.range(0, 100, 5);

var common = _.intersection(tens, eights, fives );

console.log(common);

// [0, 40, 80]

很簡(jiǎn)單,對(duì)吧?您只需傳入要比較的數(shù)組列表,Underscore 就會(huì)完成剩下的工作。


對(duì)象

除了預(yù)期的 is 檢查之外,Underscore 還提供了各種方法來克隆、擴(kuò)展和其他操作對(duì)象。

這是我最喜歡的一些。

鍵和值

有一個(gè)巨大的對(duì)象,您只需要鍵或只需要值?使用 Underscore 真是太簡(jiǎn)單了。


var Tuts = { NetTuts : 'Web Development',  WPTuts : 'WordPress',  PSDTuts : 'PhotoShop', AeTuts : 'After Effects'};
var keys = _.keys(Tuts), values = _.values(Tuts);

console.log(keys + values);

// NetTuts,WPTuts,PSDTuts,AeTutsWeb Development,WordPress,PhotoShop,After Effects

默認(rèn)值

當(dāng)您需要?jiǎng)?chuàng)建具有合理默認(rèn)值的對(duì)象(而創(chuàng)建對(duì)象時(shí)可能不會(huì)使用該默認(rèn)值)時(shí),此方法非常有用。


var tuts = { NetTuts : 'Web Development'};
var defaults = { NetTuts : 'Web Development', niche: 'Education'};

_.defaults(tuts, defaults);

console.log(tuts);

// Object { NetTuts="Web Development", niche="Education"}

函數(shù)

盡管聽起來很奇怪,Underscore 的函數(shù)可以作用于函數(shù)。大多數(shù)函數(shù)在這里解釋起來往往相當(dāng)復(fù)雜,因此我們將看一下最簡(jiǎn)單的函數(shù)。

綁定

this 是 JavaScript 中難以捉摸的一部分,往往會(huì)讓很多開發(fā)人員感到非常困惑。此方法旨在使其更容易解決。


var o = { greeting: "Howdy" }, 
	f = function(name) { return this.greeting +" "+ name; };

  var greet = _.bind(f, o); 

  greet("Jess")

這有點(diǎn)令人困惑,所以請(qǐng)留在這兒。綁定函數(shù)基本上讓您無論何時(shí)何地調(diào)用該函數(shù)都可以保留 this 的值。

當(dāng)您使用 this 被劫持的事件處理程序時(shí),這特別有用。


實(shí)用程序

為了進(jìn)一步提高交易的吸引力,Underscore 提供了大量的實(shí)用函數(shù)。由于我們的時(shí)間已經(jīng)不多了,所以讓我們看看重要的事情。

模板化

已經(jīng)有大量的模板解決方案,但 Underscore 的解決方案因其實(shí)現(xiàn)相當(dāng)小而功能相當(dāng)強(qiáng)大而值得一看。

讓我們看一個(gè)快速示例。


var data =   {site: 'NetTuts'}, template =   'Welcome! You are at <%= site %>';

var parsedTemplate = _.template(template,  data );

console.log(parsedTemplate);

// Welcome! You are at NetTuts

首先,我們創(chuàng)建數(shù)據(jù)來填充模板,然后創(chuàng)建模板本身。默認(rèn)情況下,Underscore 使用 ERB 樣式分隔符,盡管這是完全可自定義的。

有了這些,我們就可以簡(jiǎn)單地調(diào)用 template 來傳遞我們的模板和數(shù)據(jù)。我們將結(jié)果存儲(chǔ)在一個(gè)單獨(dú)的字符串中,以便稍后根據(jù)需要用于更新內(nèi)容。

請(qǐng)記住,這是 Underscore 模板的極其簡(jiǎn)單的演示。您可以使用 分隔符在模板內(nèi)使用任何 JavaScript 代碼。當(dāng)您需要迭代復(fù)雜的對(duì)象(例如 JSON 源)時(shí),您可以與 Underscore 出色的集合函數(shù)配合來快速創(chuàng)建模板。


仍然不相信你應(yīng)該選擇這個(gè)

jQuery 和 Underscore 齊頭并進(jìn)。

不不不,你們都錯(cuò)了!如果說有什么不同的話,那就是 jQuery 和 Underscore 相輔相成,齊頭并進(jìn)。真的!

看,jQuery 在一些事情上做得非常好。其中最主要的是 DOM 操作和動(dòng)畫。它不涉及較高或較低級(jí)別的任何內(nèi)容。如果像 Backbone 或 Knockout 這樣的框架處理更高級(jí)別的問題,那么 Underscore 可以解決所有相對(duì)裸機(jī)的問題。

從更廣泛的角度來看,jQuery 在瀏覽器之外沒有什么用途,因?yàn)樗拇蟛糠止δ芏寂c DOM 相關(guān)。另一方面,下劃線可以在瀏覽器或服務(wù)器端使用,沒有任何問題。事實(shí)上,Underscore 依賴它的 Node 模塊數(shù)量最多。

好了,今天就講到這里。考慮到 Underscore 的范圍,我們?cè)谶@里僅僅觸及了皮毛。請(qǐng)務(wù)必查看更多圖書館內(nèi)容,如果您有任何疑問,請(qǐng)?jiān)谙旅娴脑u(píng)論中告訴我。非常感謝您的閱讀!

The above is the detailed content of Embrace the warmth of Underscore.js. For more information, please follow other related articles on the PHP Chinese website!

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to optimize WordPress without plugins How to optimize WordPress without plugins Jul 05, 2025 am 12:01 AM

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

How to use the Transients API for caching How to use the Transients API for caching Jul 05, 2025 am 12:05 AM

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

How to optimize WordPress robots txt How to optimize WordPress robots txt Jul 13, 2025 am 12:37 AM

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

See all articles