未理解的下划线代码
Underscore Code Not Understood
在下面的javascript代码中,(下划线库):
function getStudentInfo(elem, indx, list){
//does stuff with them
}
window.addEventListener("load", function(e){
_.each(students,getStudentInfo);
}
students 是一个数组,看起来像这样
var students=[
{
"first":"Woody",
"stuff":"12",
}
//a lotta objects here
]
我的问题是下划线_.each的回调函数,(getStudentInfo) getStudentInfo 哪里知道参数是什么?传给它的参数是什么?
此处您正在对数组进行操作,最流行的 javacript 库是 lodash(称为“_”)。
回调函数总是returns一个值,它是数组的单个元素。它的工作原理与 javascript.
的 forEach 循环相同
参考https://lodash.com/docs/4.16.3#forEach
用于其文档
如果你看到 _.each
函数源代码,它会像下面的代码片段。其中
obj: 你的数组
iteratee: 回调函数
if (isArrayLike(obj)) { // checks for an array and it it is..
for (i = 0, length = obj.length; i < length; i++) { // iterate over the array elements
iteratee(obj[i], i, obj); // and pass each element to callback function
}
}
_.each(..)回调函数有3个参数
- 数组/列表的元素 -->
- 数组/列表中元素的索引 -->
- list --> 列表本身
您通过将列表作为第一个参数传递来调用 _.each() 并通过将列表一个一个地传递给回调函数来休息它
_.each("The list / array",回调函数)
在下面的javascript代码中,(下划线库):
function getStudentInfo(elem, indx, list){
//does stuff with them
}
window.addEventListener("load", function(e){
_.each(students,getStudentInfo);
}
students 是一个数组,看起来像这样
var students=[
{
"first":"Woody",
"stuff":"12",
}
//a lotta objects here
]
我的问题是下划线_.each的回调函数,(getStudentInfo) getStudentInfo 哪里知道参数是什么?传给它的参数是什么?
此处您正在对数组进行操作,最流行的 javacript 库是 lodash(称为“_”)。
回调函数总是returns一个值,它是数组的单个元素。它的工作原理与 javascript.
的 forEach 循环相同参考https://lodash.com/docs/4.16.3#forEach
用于其文档
如果你看到 _.each
函数源代码,它会像下面的代码片段。其中
obj: 你的数组
iteratee: 回调函数
if (isArrayLike(obj)) { // checks for an array and it it is..
for (i = 0, length = obj.length; i < length; i++) { // iterate over the array elements
iteratee(obj[i], i, obj); // and pass each element to callback function
}
}
_.each(..)回调函数有3个参数
- 数组/列表的元素 -->
- 数组/列表中元素的索引 -->
- list --> 列表本身
您通过将列表作为第一个参数传递来调用 _.each() 并通过将列表一个一个地传递给回调函数来休息它
_.each("The list / array",回调函数)