javascript _(variable_name) 在javascript中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16046532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does _(variable_name) mean in javascript?
提问by Charles Gao
I came across the following javascript code:
我遇到了以下 javascript 代码:
this.removeEdge = function(source, target) {
if(!_states[source]) return;
var children = _states[source].children,
index = _(children).indexOf(target);
if(index !== -1) children.splice(index, 1);
};
What does _(children) mean?
_(儿童)是什么意思?
回答by zzzzBov
_
is a valid variable identifier in JavaScript, and could theoretically refer to anything. Using _(...)
with function syntax implies that _
is a function.
_
是 JavaScript 中的有效变量标识符,理论上可以指代任何东西。使用_(...)
with 函数语法意味着这_
是一个函数。
That said, it is commonly used by the underscore.jslibrary, however if you're looking at minified code, it's quite possibly being used as another single-character variable name to save on file size.
也就是说,它通常由underscore.js库使用,但是如果您正在查看缩小的代码,它很可能被用作另一个单字符变量名称以节省文件大小。
In your example provided, it appears that underscore.js is being used to treat children
as a collection, so that the indexOf
functioncan be applied to the collection. This would be similar to calling:
在您提供的示例中,underscore.js 似乎被用作children
集合,以便可以将该indexOf
函数应用于集合。这类似于调用:
_.indexOf(children, target);
回答by jahmezz
Came looking for an answer to this and managed to find one. The _(variable) statement wraps underscore around the variable. According to this linkin the "Object-Oriented and Functional Styles" section,
来寻找这个问题的答案并设法找到了一个。_(variable) 语句用下划线包裹变量。根据“面向对象和功能样式”部分中的这个链接,
index = _(children).indexOf(target);
is equivalent to
相当于
index = _.indexOf(children, target);
The first is written in object-oriented style, which allows chaining of functions. Their example is as follows:
第一个是以面向对象的风格编写的,它允许链接函数。他们的例子如下:
_(lyrics).chain()
.map(function(line) { return line.words.split(' '); })
.flatten()
.reduce({}, function(counts, word) {
counts[word] = (counts[word] || 0) + 1;
Each of these functions returns the underscore function wrapping lyrics, allowing chained manipulation of the lyrics variable.
这些函数中的每一个都返回包装歌词的下划线函数,允许对歌词变量进行链式操作。
Underscore changelog:
下划线变更日志:
0.4.0 — November 7, 2009: All Underscore functions can now be called in an object-oriented style, like so: _([1, 2, 3]).map(...);. Original patch provided by Marc-André Cournoyer. Wrapped objects can be chained through multiple method invocations. A functions method was added, providing a sorted list of all the functions in Underscore.
0.4.0 — 2009 年 11 月 7 日:现在可以以面向对象的方式调用所有 Underscore 函数,如下所示:_([1, 2, 3]).map(...);。Marc-André Cournoyer 提供的原始补丁。包装的对象可以通过多个方法调用链接起来。添加了一个函数方法,提供了 Underscore 中所有函数的排序列表。