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

时间:2019-03-18 19:09:23

标签: javascript jslint

如何使用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;
}

有什么作用?

2 个答案:

答案 0 :(得分:2)

forEach只是遍历列表,但不返回任何内容。因此,请改用map并返回新创建的对象。

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);
  });
}

另一个问题是peaks不在loadAudioMeterHistory范围之外。因此,请让函数返回可以传递给下一个函数调用的函数。

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);
  });
}

答案 1 :(得分:0)

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

model_checkpoint_path = <path to checkpoint>
c1 = ModelCheckpoint(model_checkpoint_path, 
                     save_best_only=True,
                     monitor=...)
c2 = ReduceLRBacktrack(best_path=model_checkpoint_path, monitor=...)

对于第二个功能,使用如下所示的forEach():

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);
  });
}