javascript - 用数组嵌套 d3.max

标签 javascript arrays d3.js

我有一个像这样的数组。

data = [
  [
    {x: 1, y: 40},
    {x: 2, y: 43},
    {x: 3, y: 12},
    {x: 4, y: 60},
    {x: 5, y: 63},
    {x: 6, y: 23}
 ], [
    {x: 1, y: 12},
    {x: 2, y: 5},
    {x: 3, y: 23},
    {x: 4, y: 18},
    {x: 5, y: 73},
    {x: 6, y: 27}
 ], [
    {x: 1, y: 60},
    {x: 2, y: 49},
    {x: 3, y: 16},
    {x: 4, y: 20},
    {x: 5, y: 92},
    {x: 6, y: 20}
  ] 
];

我可以通过嵌套的 d3.max() 调用找到 data 的最大 y 值:

d3.max(data, function(d) {
  return d3.max(d, function(d) {
    return d.y;
  });
});

我很难理解这段代码的实际工作原理。我知道 d3.max() 函数的第二个参数指定了一个访问器函数 - 但我对两次调用 d3.max() 与访问器函数的确切关系感到困惑。

我想我要的是 javascript 如何解释这段代码的演练。我已经在控制台上完成了它,但不幸的是它没有帮助。

最佳答案

有时一切都与变量的命名有关:

// the outer function iterates over the outer array
// which we can think of as an array of rows

d3.max(data, function(row) {

  // while the inner function iterates over the inner
  // array, which we can think of as an array containing
  // the columns of a single row. Sometimes also called
  // a (table) cell.

  return d3.max(row, function(column) {
    return column.y;
  });

});

您可以在此处找到 d3.max 函数的源代码:https://github.com/d3/d3.github.com/blob/8f6ca19c42251ec27031376ba9168f23b9546de4/d3.v3.js#L69

关于javascript - 用数组嵌套 d3.max,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688982/

相关文章:

javascript - Dropzone.js - 显示存储在 app_data 文件夹中的图像

javascript - 使用 setInterval 隐藏和显示循环

javascript - 在 mousedown 元素之外捕获 mouseup 的最佳方法

javascript - 仅当主体具有 X 类时才运行代码?

javascript - 根据提示进行数组存储

arrays - 如何在 Rails 4.2 表单中提交字符串数组

JavaScript: "SyntaxError: missing ) after argument list"文件最后一行

c - 使用 for 循环从数组中删除对象

javascript - d3 鼠标参数与 jquery

d3.js - SVG 路径超出 d3 画笔上的图表区域