如何刷新数组的内容?

时间:2018-04-09 18:41:04

标签: javascript

我有一个数组,它在一秒的空间内取值并计算平均值。然后该数组永久存储值。我需要它们在计算平均值后删除值。我尝试使用calculateAveragelevelMeasurements = [];清除levelMeasurements = 0;函数末尾的数组,但这不起作用。

非常感谢任何有关这方面的帮助,谢谢!

我的代码:

var levelMeasurements = [];

function collectLevelMeasurements() {
    levelMeasurements.push(averagingLevel);
}
var collectInterval = window.setInterval(collectLevelMeasurements, 0);

function calculateAverage() {
    window.clearInterval(collectInterval);

    var avg = 0;

    for (counter = 0; counter < levelMeasurements.length; counter++) {
        avg += levelMeasurements[counter] / levelMeasurements.length;
    }

    averageAbsoluteLevel = Math.abs(avg);
    averageDbLevel = Tone.gainToDb(averageAbsoluteLevel) * scale + offset;

    console.log("Measure for 5 minutes: average level is:" + averageDbLevel);

}
window.setInterval(calculateAverage, 1000);

2 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

levelMeasurements.length = 0.

或者在此处提及更多解决方案:How do I empty an array in JavaScript?

答案 1 :(得分:0)

第一次调用collectInterval后,calculateAverage超时永远不会恢复,除非问题是代码中看不到的其他问题。

在您的代码calculateAverage中每1000毫秒调用一次,但是在第一个window.clearInterval之后,levelMeasurements中存储的值不会更新。

我制作了一个没有Tone lib的简化片段:

&#13;
&#13;
var levelMeasurements = [];

//added this as a easy source of values
let count = 0;

function collectLevelMeasurements() {
    // levelMeasurements.push(averagingLevel);
  levelMeasurements.push(count++);
}
var collectInterval = window.setInterval(collectLevelMeasurements, 0);

function calculateAverage() {
    window.clearInterval(collectInterval);

    var avg = 0;

    for (counter = 0; counter < levelMeasurements.length; counter++) {
        avg += levelMeasurements[counter] / levelMeasurements.length;
    }

    averageAbsoluteLevel = Math.abs(avg);
    averageDbLevel = averageAbsoluteLevel;
  
    //prolly dont need tone lib for this example
    // averageDbLevel = Tone.gainToDb(averageAbsoluteLevel) * scale + offset;

    console.log("Measure for 5 minutes: average level is:" + averageDbLevel);
  
    //reset these variables
    levelMeasurements = [];
    count = 0;
    console.log(levelMeasurements)//empty array at this point
    //reset the collectInterval!
    collectInterval = window.setInterval(collectLevelMeasurements, 0);

}
window.setInterval(calculateAverage, 1000);
&#13;
&#13;
&#13;