I have a quote long javascript int array such:
var heights = new Array(120, 123, 145, 130, 131, 139, 164, 164, 165, 88, 89);
I have to calculate the average value three items per time, including the last two numers (88, 89). How can I do a correct loop in order to incluse these last values (which are only two) ?
This is the way to calculate an average for given array from index to index:
var grades = [1,2,3,4,5,6,7,8,9,0];
var average = calculateAverage(grades,0,9);
console.log(average);
function calculateAverage(arr,start,end){
var total =0;
for(var i=start; i<=end; i++){
total+=arr[i];
}
var diff = (end-start)+1;
var avg = total/diff;
return avg;
}
Using Rest parameter and for...of loop for an array...
function average(...nums) { let total = 0; for(const num of nums) { total += num; } let avr = total / arguments.length; return avr; } console.log(average(2, 6)); console.log(average(2, 3, 3, 5, 7, 10)); console.log(average(7, 1432, 12, 13, 100)); console.log(average());
Problem: for no arguments - console.log(average()); - Returns Null where the correct answer must be 0. Any good shorthand solution here?
Thanks to javascript you can perfectly do something like this.
var heights = new Array(120, 123, 145, 130, 131, 139, 164, 164, 165, 88, 89); var results = []; for( var i = 0; i < heights.length; i += 3 ){ results[results.length] = (heights[i] + (heights[i+1]||0) + (heights[i+2]||0))/Math.min(3,heights.length-i); } alert( results.toString() );
heights[i+1]||0
simply means that if heights[i+1]
doesn't exist, thus returns null
, the whole thing will be equal to 0 (for more information, just google javascript short circuit operators . As many people commented, maybe you didn't do enough research on your task ;)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.