我在理解 Array.map
的概念时遇到问题。我确实去了 Mozilla 和 Tutorials Point,但他们提供的相关信息非常有限。
这就是我使用 Array.map
的方式。它有点复杂(涉及到一些 d3.js;忽略它)
var mapCell = function (row) {
return columns.map(function(column) {
return { column : column, value : getColumnCell(row, column) }
})
}
//getColumnCell is a function defined in my code
//columns is array defined at the top of my code
我不明白这段代码到底在做什么。我知道它会返回一个新数组和其他东西,但这部分有点棘手!
如果你想通过我的代码:http: //jsfiddle.net/ddfsb/2/
我正在使用控制台来真正了解代码中发生的事情。查看提供的答案,我已经清楚地理解了 array.map
的概念。现在剩下的唯一部分是参数行和列,但是提供的小提琴中的行和行以及列和列之间存在差异
var rows//completely ok
var columns//completely ok
funcion(row)//here,source of row is unknown.getColumncell function utilizes this parameter further making it more critical
function(column)//source of column is unknown..getColumncell function utilizes this parameter further making it more critical
原文由 user2412575 发布,翻译遵循 CC BY-SA 4.0 许可协议
让我们稍微重写一下,然后从内到外开始工作。
function(column)
部分本质上是一个函数,它将一列作为参数,并返回一个具有两个属性的新对象:columns.map()
部分调用Array.map
函数,它接受一个数组和一个函数,并为它的每个最后一项运行该函数,并返回结果。即,如果输入是数组[1, 2, 3, 4, 5]
并且函数类似于isEven
,结果将是数组[false, true, false, true, false]
在您的例子中,输入是列,输出是对象列表,每个对象都有一个列和一个值属性。Lastly, the
var mapCell = function (row)
part declares that the variablemapCell
will contain a function of one variable calledrow
- and this is the samerow
在内部函数中使用。在一句话中,这行代码声明了一个函数,该函数在运行时将获取一行并返回该行所有列的值。