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!
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);Copy after loginIt'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);Copy after loginI 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);Copy after loginThe 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);Copy after loginThere'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"]Copy after loginUsing
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+"]Copy after login由于我注意到名称末尾缺少加号,因此我将它们添加到提取的数组中。
这里您不仅限于简单的串联。您可以根据自己的意愿随意修改传递的值。
全部
all
如果您需要检查集合中的每个值是否满足特定条件,则非常有用。例如,检查学生是否通过了每个科目。var Scores = [95, 82, 98, 78, 65]; var hasPassed = _(Scores).all(function (value){return value>50; }); console.log(hasPassed); // trueCopy after login
数组
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]Copy after login当您解析巨大的数据集并需要清除重复项时,这非常方便。请记住,仅计算元素的第一个实例,因此保留原始顺序。
范围
一种非常方便的方法,可让您创建“范围”或数字列表。让我们看一个超级简单的例子。
var tens = _.range(0, 100, 10); console.log(tens); // [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]Copy after login该方法的参数依次为起始值、结束值和步长值。如果您想知道,使用负步长值会导致递减范围。
交叉路口
此方法将两个数组相互比较,并返回在所有传递的数组中找到的元素列表,即集合论中的交集。
让我们扩展前面的示例来看看它是如何工作的。
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]Copy after login很简单,对吧?您只需传入要比较的数组列表,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 EffectsCopy after login默认值
当您需要创建具有合理默认值的对象(而创建对象时可能不会使用该默认值)时,此方法非常有用。
var tuts = { NetTuts : 'Web Development'}; var defaults = { NetTuts : 'Web Development', niche: 'Education'}; _.defaults(tuts, defaults); console.log(tuts); // Object { NetTuts="Web Development", niche="Education"}Copy after login
函数
尽管听起来很奇怪,Underscore 的函数可以作用于函数。大多数函数在这里解释起来往往相当复杂,因此我们将看一下最简单的函数。
绑定
this
是 JavaScript 中难以捉摸的一部分,往往会让很多开发人员感到非常困惑。此方法旨在使其更容易解决。var o = { greeting: "Howdy" }, f = function(name) { return this.greeting +" "+ name; }; var greet = _.bind(f, o); greet("Jess")Copy after login这有点令人困惑,所以请留在这儿。绑定函数基本上让您无论何时何地调用该函数都可以保留
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 NetTutsCopy after login首先,我们创建数据来填充模板,然后创建模板本身。默认情况下,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!