简体   繁体   English

循环嵌套迭代的Javascript

[英]Javascript for loop nested iteration

I'm trying to iterate through a large array of values and collect an average of one of the values for each second. 我正在尝试遍历一大堆值,并每秒收集一个值的平均值。 I can't get this code to work properly, and as far as I can see the issue is with the nested while loop. 我无法使此代码正常工作,据我所知,问题出在嵌套的while循环中。 am I making a scope error that's preventing me from iterating the for loop index? 我是否在发生范围错误,使我无法迭代for循环索引?

The data is a timestamp in ms and a radiation count. 数据是一个以毫秒为单位的时间戳和一个辐射计数。 a.data[i][0] is the timestamp and a.data[i][26] is the count. a.data[i][0]是时间戳, a.data[i][26]是计数。

for (i = 0; i < a.data.length; i++){
    // counts is the count of radiation over the last timeframe
    var counts = 0;
    // t1 is the start time 
    // t2 is the current iteration time
    var t1, t2 = a.data[i][0];
    while ((t2 - t1) < 1000){
        t2 = a.data[i][0];
        counts += a.data[i][26];
        i++;
    }
    // Geiger Data is an array of { x:(time), y:(value)} datapoints.
    GeigerData.push({x: (t1/1000), y: counts});
}

You problem stems from this line: 您的问题源于此行:

 var t1, t2 = a.data[i][0];

Defining JS variables doesn't work like that, and in your code t1 is always undefined. 定义JS变量并不能那样工作,并且在代码中t1始终是未定义的。 What you really want is 你真正想要的是

 var t1 = a.data[i][0];
 var t2 = t1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM