1

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. am I making a scope error that's preventing me from iterating the for loop index?

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.

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});
}
asked Nov 16, 2014 at 0:12

1 Answer 1

2

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. What you really want is

 var t1 = a.data[i][0];
 var t2 = t1;
answered Nov 16, 2014 at 0:18
Sign up to request clarification or add additional context in comments.

2 Comments

This could also be done var t1 = t2 = a.data[i][0]
@JonathanCrowe - technically, yes, you could do that, but you super don't want to. Your code is the same as doing this: var t1 = a.data[i][0]; t2 = t1; This puts t2 in the global scope, by not using var. See this fiddle: jsfiddle.net/ucyewprL

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.