我有一个数组,它在一秒的空间内取值并计算平均值。然后该数组永久存储值。我需要它们在计算平均值后删除值。我尝试使用calculateAverage
和levelMeasurements = [];
清除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);
答案 0 :(得分:0)
答案 1 :(得分:0)
第一次调用collectInterval
后,calculateAverage
超时永远不会恢复,除非问题是代码中看不到的其他问题。
在您的代码calculateAverage
中每1000毫秒调用一次,但是在第一个window.clearInterval
之后,levelMeasurements中存储的值不会更新。
我制作了一个没有Tone lib的简化片段:
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;