如何编写这些函数以使用 forEach() 语句?

How can I write these functions to use a forEach() statement?

如何使用 forEach() 方法编写这些(工作)函数:

function loadAudioMeterHistory(cell) {
    var peaks = new Array(4);

    for (var i = 0; i < peaks.length; i++) {
        var peak,
            age;

        peak = cell.getAttribute("data-peak-" + i);
        age  = cell.getAttribute("data-age-" + i);

        peaks[i] = new Peak(peak, age);
    }

    return peaks;
}
function setAudioMeterHistory(cell, peaks) {
    for (var i = 0; i < peaks.length; i++) {
        cell.setAttribute("data-peak-" + i, peaks[i].peak);
        cell.setAttribute("data-age-" + i,  peaks[i].age);
    }
}

我的尝试如下:

function loadAudioMeterHistory(cell) {
    "use strict";
    var peaks = new Array(4);

    peaks.forEach(function(item, index) {
        var p = cell.getAttribute("data-peak-" + index);
        var a = cell.getAttribute("data-age-" + index);

        item = new Peak(p, a);
    });

    return peaks;
}
function setAudioMeterHistory(cell, peaks) {
    "use strict";
    peaks.forEach(function(item, index) {
        cell.setAttribute("data-peak-" + index, item.peak);
        cell.setAttribute("data-age-"  + index, item.age);
    });
}

其行为不同,因为 peaks 从未正确创建。精明的 javascripter 无疑会认识到我正在尝试 jslint.com 我的代码。

Peak() 方法(为简洁起见)很简单:

function Peak(peak, age) {
    this.peak = peak;
    this.age  = age;
}

什么给了?

forEach 只是遍历一个列表而不是 return 任何东西。因此,请改用 map 并 return 新创建的对象。

function loadAudioMeterHistory(cell) {
  "use strict";

  var peaks = [0, 1, 2, 3].map(function(item, index) {
    var p = cell.getAttribute("data-peak-" + index);
    var a = cell.getAttribute("data-age-" + index);

    return new Peak(p, a);
  });
}

还有一个问题是 peaksloadAudioMeterHistory 范围之外不可用。所以有函数 return 可以传递给下一个函数调用。

function loadAudioMeterHistory(cell) {
  "use strict";

  return [0, 1, 2, 3].map(function(item, index) {
    var p = cell.getAttribute("data-peak-" + index);
    var a = cell.getAttribute("data-age-" + index);

    return new Peak(p, a);
  });
}

function setAudioMeterHistory(cell) {
  "use strict";

  var peaks = loadAudioMeterHistory(cell);

  peaks.forEach(function(item, index) {
    cell.setAttribute("data-peak-" + index, item.peak);
    cell.setAttribute("data-age-" + index, item.age);
  });
}

您可以使用 Array.from() 其第二个参数是一个函数来填充数组:

function loadAudioMeterHistory(cell) {
  return Array.from({ length: 4 }, (_, i) => {
    const peak = cell.getAttribute('data-peak-' + i);
    const age  = cell.getAttribute('data-age-' + i);
    return new Peak(peak, age);
  });
}

对于第二个函数,像这样使用 forEach():

function setAudioMeterHistory(cell, peaks) {
  peaks.forEach(({ peak, age }) => {
    cell.setAttribute('date-peak-' + i, peak);
    cell.setAttribute('data-age-' + i, age);
  });
}