search
HomeCMS TutorialWordPressEmbrace the warmth of Underscore.js

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

让我们以前面的示例为例并对其进行一些扩展。


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+"]

由于我注意到名称末尾缺少加号,因此我将它们添加到提取的数组中。

这里您不仅限于简单的串联。您可以根据自己的意愿随意修改传递的值。

全部

all 如果您需要检查集合中的每个值是否满足特定条件,则非常有用。例如,检查学生是否通过了每个科目。


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

console.log(hasPassed);

// true

数组

Underscore 有很多专门处理数组的函数,这是非常受欢迎的,因为与其他语言相比,JavaScript 提供的处理数组的方法非常少。

Uniq

此方法基本上解析数组并删除所有重复元素,只为您提供唯一元素。


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]

当您解析巨大的数据集并需要清除重复项时,这非常方便。请记住,仅计算元素的第一个实例,因此保留原始顺序。

范围

一种非常方便的方法,可让您创建“范围”或数字列表。让我们看一个超级简单的例子。


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

console.log(tens);

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

该方法的参数依次为起始值、结束值和步长值。如果您想知道,使用负步长值会导致递减范围。

交叉路口

此方法将两个数组相互比较,并返回在所有传递的数组中找到的元素列表,即集合论中的交集。

让我们扩展前面的示例来看看它是如何工作的。


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]

很简单,对吧?您只需传入要比较的数组列表,Underscore 就会完成剩下的工作。


对象

除了预期的 is 检查之外,Underscore 还提供了各种方法来克隆、扩展和其他操作对象。

这是我最喜欢的一些。

键和值

有一个巨大的对象,您只需要键或只需要值?使用 Underscore 真是太简单了。


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

默认值

当您需要创建具有合理默认值的对象(而创建对象时可能不会使用该默认值)时,此方法非常有用。


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

_.defaults(tuts, defaults);

console.log(tuts);

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

函数

尽管听起来很奇怪,Underscore 的函数可以作用于函数。大多数函数在这里解释起来往往相当复杂,因此我们将看一下最简单的函数。

绑定

this 是 JavaScript 中难以捉摸的一部分,往往会让很多开发人员感到非常困惑。此方法旨在使其更容易解决。


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

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

  greet("Jess")

这有点令人困惑,所以请留在这儿。绑定函数基本上让您无论何时何地调用该函数都可以保留 this 的值。

当您使用 this 被劫持的事件处理程序时,这特别有用。


实用程序

为了进一步提高交易的吸引力,Underscore 提供了大量的实用函数。由于我们的时间已经不多了,所以让我们看看重要的事情。

模板化

已经有大量的模板解决方案,但 Underscore 的解决方案因其实现相当小而功能相当强大而值得一看。

让我们看一个快速示例。


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

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

console.log(parsedTemplate);

// Welcome! You are at NetTuts

首先,我们创建数据来填充模板,然后创建模板本身。默认情况下,Underscore 使用 ERB 样式分隔符,尽管这是完全可自定义的。

有了这些,我们就可以简单地调用 template 来传递我们的模板和数据。我们将结果存储在一个单独的字符串中,以便稍后根据需要用于更新内容。

请记住,这是 Underscore 模板的极其简单的演示。您可以使用 分隔符在模板内使用任何 JavaScript 代码。当您需要迭代复杂的对象(例如 JSON 源)时,您可以与 Underscore 出色的集合函数配合来快速创建模板。


仍然不相信你应该选择这个

jQuery 和 Underscore 齐头并进。

不不不,你们都错了!如果说有什么不同的话,那就是 jQuery 和 Underscore 相辅相成,齐头并进。真的!

看,jQuery 在一些事情上做得非常好。其中最主要的是 DOM 操作和动画。它不涉及较高或较低级别的任何内容。如果像 Backbone 或 Knockout 这样的框架处理更高级别的问题,那么 Underscore 可以解决所有相对裸机的问题。

从更广泛的角度来看,jQuery 在浏览器之外没有什么用途,因为它的大部分功能都与 DOM 相关。另一方面,下划线可以在浏览器或服务器端使用,没有任何问题。事实上,Underscore 依赖它的 Node 模块数量最多。

好了,今天就讲到这里。考虑到 Underscore 的范围,我们在这里仅仅触及了皮毛。请务必查看更多图书馆内容,如果您有任何疑问,请在下面的评论中告诉我。非常感谢您的阅读!

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
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
How does WordPress's plugin ecosystem enhance its CMS capabilities?How does WordPress's plugin ecosystem enhance its CMS capabilities?May 14, 2025 am 12:20 AM

WordPresspluginssignificantlyenhanceitsCMScapabilitiesbyofferingcustomizationandfunctionality.1)Over50,000pluginsallowuserstotailortheirsiteforSEO,e-commerce,andsecurity.2)Pluginscanextendcorefeatures,likeaddingcustomposttypes.3)However,theycancausec

Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment