javascript函数参数中的下划线是什么意思? [英] What is the meaning of an Underscore in javascript function parameter?
问题描述
我正在浏览用javascript编写的图表库之一的代码,其中我看到将下划线(_)作为函数参数进行传递.是什么意思?
I was going through the code of one of the chart library written in javascript, wherein I've seen passing underscore(_) as a function parameter. What does that mean?
例如
chart.x = function(_) {
if (!arguments.length) return lines.x;
lines.x(_);
lines2.x(_);
return chart;
};
有人可以对此进行更新吗...谢谢.
Can someone please update on this...Thanks.
推荐答案
下划线符号_
在JavaScript中是有效的标识符,在您的示例中,它被用作函数参数.
The underscore symbol _
is a valid identifier in JavaScript, and in your example, it is being used as a function parameter.
单个下划线是一些Javascript程序员用来向其他程序员指示他们应该忽略此绑定/参数"的约定.由于JavaScript不会进行参数计数检查,因此可以完全省略该参数.
A single underscore is a convention used by some javascript programmers to indicate to other programmers that they should "ignore this binding/parameter". Since JavaScript doesn't do parameter-count checking the parameter could have been omitted entirely.
此符号通常(再次按照惯例)与fat-arrow函数结合使用,以使它们更简洁易读,如下所示:
This symbol is often used (by convention again) in conjunction with fat-arrow functions to make them even terser and readable, like this:
const fun = _ => console.log('Hello, World!')
fun()
在这种情况下,该函数不需要运行任何参数,因此开发人员已使用下划线作为惯例来表明这一点.可以这样写同样的东西:
In this case, the function needs no params to run, so the developer has used the underscore as a convention to indicate this. The same thing could be written like this:
const fun = () => console.log('Hello, World!')
fun()
区别在于第二个版本是不带参数的函数,但是第一个版本有一个名为_的参数,该参数将被忽略.但是,它们有所不同,第二个版本比较冗长(多了1个字符),因此比较安全.
The difference is that the second version is a function with no parameters, but the first version has a parameter called _ that is ignored. These are different though and the second version is safer, if slightly more verbose (1 extra character).
还要考虑类似
arr.forEach(function (_, i) {..})
_
表示不使用第一个参数.
Where _
indicates the first parameter is not to be used.
在使用流行的lodash或下划线库时,使用这样的下划线会造成混乱.
The use of underscores like this can get very confusing when using the popular lodash or underscore libraries.
这篇关于javascript函数参数中的下划线是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!